For checked exceptions (not any RuntimeException
), they must be either handled or thrown by the method that calls another method that throws the exception. This is also explained in more depth in the tutorial by Oracle on Exceptions.
This example is based on your code:
class Testing{
public static void main(String[] args) {
Third t = new Third();
t.method3();
}
}
and it will print:
Caught the exception
Divided by zero
Added the missing implementation of CustomException
:
class CustomException extends Exception{
CustomException(){
super();
}
CustomException(String message){
super(message);
}
}
Note that your code would never get to actually throwing your exception, as division by zero would be thrown first. ArithmeticException
is a RuntimeException
and therefore not a checked exception, and it doesn't need or warrant any declaration. I've removed it so your exception is thrown:
class First {
protected void method1() throws CustomException {
// will cause "java.lang.ArithmeticException: / by zero" not CustomException
// int number=10/0;
// System.out.println("method 1" + number);
throw new CustomException("Divided by zero");
}
} // missing end brace
The reason why your Second
's method call "won't let me pass" is because you're throwing an Exception
in method1
which you are calling in your Second
's method call. So you need to either wrap your call to method1()
in a try-catch block, or throws
it. Since you "want to catch it from third", you need to throws
it in the declaration of the method:
class Second extends First {
// error: unreported exception CustomException; must be caught or declared to be thrown
// protected void method2() { // your version
protected void method2() throws CustomException {
method1();
}
} // missing end brace
This is unchanged, except for the added brace:
class Third extends Second {
protected void method3(){
try {
method2();
} catch (CustomException ex) {
System.out.println("Caught the exception");
System.out.println(ex.getMessage());
}
}
} // missing end brace