Previous | Home | Next |
Try and catch block used for fixing the error and stop automatic termination of program. Every try must be followed by one or more catch or finally. One example of multiple catch is given below.
/* * Save as multicatchexp.java * Implementing multiple catch */ package exceptionhandlingexmp; class impmulticatch { int b, a[]={1,2,3,4,5}; impmulticatch(int num) { b=num; } public void demo(int c) { try{ b=b/c; for(int i=0;i<=a.length;i++) { System.out.println(a[i]); } } catch(ArithmeticException e) { System.out.println("Divide by zero"+e); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Index out of bound"+e); } } } public class multicatchexp { public static void main(String[] str) { impmulticatch obj1=new impmulticatch(10); impmulticatch obj2=new impmulticatch(20); obj1.demo(10); obj2.demo(0); } }
Output:
1 2 3 4 5 Index out of boundjava.lang.ArrayIndexOutOfBoundsException: 5 Divide by zerojava.lang.ArithmeticException: / by zero
Previous | Home | Next |