Complete the code to declare a custom exception class named MyException.
public class MyException extends [1] { public MyException(String message) { super(message); } }
Custom exceptions usually extend Exception to create checked exceptions.
Complete the code to throw the custom exception MyException with a message.
if (value < 0) { throw new [1]("Value cannot be negative"); }
We throw the custom exception MyException to signal a specific error.
Fix the error in the method signature to declare that it throws MyException.
public void checkValue(int value) [1] { if (value < 0) { throw new MyException("Negative value"); } }
The method must declare throws MyException to indicate it can throw this checked exception.
Fill both blanks to catch the custom exception and print its message.
try { checkValue(-5); } catch ([1] e) { System.out.println(e.[2]()); }
Catch the custom exception MyException and use getMessage() to print the error message.
Fill all three blanks to create a custom exception, throw it, and catch it properly.
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()); } } }
Define a custom exception class CustomException, throw it, and catch it by the same class name.