The right way to do this, btw, is to just allow ArithmeticException
to end the program if needed.
public class Exam {
private static void div(int i, int j) throws ArithmeticException {
System.out.println(i / j);
}
public static void main(String[] args) throws Exception {
div(5, 0);
}
}
Much cleaner and clearer, and the exception provides important debugging information that you will need to find your runtime errors.
What I think you’d need to do to catch the second exception is to nest the try
. You can have several catch
for the same try
and they all only catch one exception, they don’t cascade or go in order. To catch an exception that is thrown by a catch
you’d need another try
block.
private static void div(int i, int j) {
try { // NESTED HERE
try {
System.out.println(i / j);
} catch(ArithmeticException e) {
Exception ex = new Exception(e);
throw ex;
}
// THIS GOES WITH THE OUTER NESTED 'try'
} catch( Exception x ) {
System.out.println( "Caught a second exception: " + x );
}
}
But again, you shouldn’t do this. Allowing the original exception to be thrown is the far better choice.
3
solved Why do I Have to append the method signature with throws Exception when try block is being used?