Using try and catch • General form: try { // block of code to monitor for errors } catch( ExceptionType exObj ) { // handle ExceptionType errors } … // catch blocks for other types of errors
More about try and catch • If the code in the try block throws an exception, the catch block for the type of exception thrown is executed. • If there is no catch block for the type of exception thrown, the exception is handled elsewhere (discussed later). • If the code in the try block does not throw any exceptions, no catch block is executed.
Try-catch Example try { int x = 3/y; System.out.println("Prints only if y is non-zero."); } catch(DivideByZeroException exc) { System.out.println("Tried to divide by zero."); } System.out.println("After catch.");
• If y is zero, then "Tried to divide by zero." is
Using the Thrown Exception Objects • The catch block receives the exception object as a parameter. • That exception object has methods inherited from Throwable that you can call to get further information about the exception.
Example of a finally Block try { int x = 3/0; } catch(DivideByZeroException exc) { System.out.println("Divide by zero"); } finally { System.out.println("Leaving try"); }