0
0
Javaprogramming~10 mins

Why custom exceptions are needed in Java - Test Your Understanding

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare a custom exception class named MyException.

Java
public class MyException extends [1] {
    public MyException(String message) {
        super(message);
    }
}
Drag options to blanks, or click blank then click option'
AError
BException
CThrowable
DRuntimeException
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Extending Error or Throwable directly is not common for custom exceptions.
2fill in blank
medium

Complete the code to throw the custom exception MyException with a message.

Java
if (value < 0) {
    throw new [1]("Value cannot be negative");
}
Drag options to blanks, or click blank then click option'
AIllegalArgumentException
BException
CMyException
DRuntimeException
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Throwing generic exceptions like Exception or RuntimeException instead of the custom one.
3fill in blank
hard

Fix the error in the method signature to declare that it throws MyException.

Java
public void checkValue(int value) [1] {
    if (value < 0) {
        throw new MyException("Negative value");
    }
}
Drag options to blanks, or click blank then click option'
Athrow Exception
Bthrow MyException
Cthrows Exception
Dthrows MyException
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using 'throw' instead of 'throws' in the method signature.
4fill in blank
hard

Fill both blanks to catch the custom exception and print its message.

Java
try {
    checkValue(-5);
} catch ([1] e) {
    System.out.println(e.[2]());
}
Drag options to blanks, or click blank then click option'
AMyException
BgetMessage
CprintStackTrace
DException
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Catching generic Exception instead of MyException.
Using printStackTrace() instead of getMessage() for printing.
5fill in blank
hard

Fill all three blanks to create a custom exception, throw it, and catch it properly.

Java
public class [1] extends Exception {
    public [1](String msg) {
        super(msg);
    }
}

public class Test {
    public static void main(String[] args) {
        try {
            throw new [2]("Error happened");
        } catch ([3] e) {
            System.out.println(e.getMessage());
        }
    }
}
Drag options to blanks, or click blank then click option'
ACustomException
DMyException
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using different names for the exception class in declaration, throw, and catch.