We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 14
Multiple catch Statements
it is possible to have more than one catch
statement in the catch block as illustrated below: ........ .......... try { statement; // generates an exception } catch (Exception-type1 e) { statement; // processes the exception type 1 } catch (Exception-type2 e) { statement; // processes the exception type2 } ........ catch (Exception-typeN e) { statement; // processes the exception typeN } When an exception in a try block is generated each catch statement is inspected in order, the first statement whose parameter matches with the exception object will be executed and the remaining statements will be skipped. finally statement finally statement can be used to handle an exception that is not caught by any of the previous catch statement .finally block is executed whether or not exception is thrown General Form: try { ....... } catch(...) { .... } catch(...) { .... } .... finally { .... } Program to demonstrate exception class Main { public static void main(String args[]) { int d, a; int b[]={5,10}; try { // monitor a block of code. //d = 0; //a = 42 / d; b[40]=10; } catch (ArithmeticException e) { System.out.println("Division by zero."); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("array index out of bounds exception"); } finally{ System.out.println("After catch statement."); } } } output javac Main.java java Main array index out of bounds exception After catch statement. throws If a method is capable of causing an exception that it does not handle, it must specify this behaviour by including a throws clause in the method’s declaration. If they are not, a compile-time error will result. general form of a throws clause: type method-name(parameter-list) throws exception-list { // body of method } Here, exception-list is a comma-separated list of the exceptions that a method can throw. class Exc2{ static void divide() throws ArithmeticException { int d, a; d = 0; a = 42 / d; } public static void main(String args[]) { try { // monitor a block of code. divide(); } catch (ArithmeticException e) { // catch divide-by- zero error System.out.println("Caught Exception:Division by zero."); } } } output javac Exc2.java java Exc2