You are on page 1of 3

Question- Write a program to create you own exception.

CODE: class A extends Exception { String s; A() { s="My own exception"; } public String toString() { return s; } } class B { void exp() throws A { throw new A(); } } class Demo1 { public static void main(String arg[]) { B b1=new B(); try { b1.exp(); } catch(Exception e) { System.out.println(e); } } }

OUTPUT: cd C:\Program Files\Java\jdk1.6.0_26\bin javac Demo1.java java Demo1 My own exception

Question-WAP to handle ArithmeticException. CODE: class NewClass { public static void main(String arg[]) { int i=5; int j=1; try { int z=i/j; System.out.println(z); try { int w=i/(j-1); System.out.println(w); } catch(ArithmeticException e) { System.out.println("Inner catch handled exception");} } catch(ArithmeticException e) { System.out.println("Outer catch exception handled"); } } }

OUTPUT: cd C:\Program Files\Java\jdk1.6.0_26\bin javac NewClass.java java NewClass 5 Inner catch handled exception

Question-WAP to handle ArrayIndexOutOfBoundsException. CODE: class NewClass1 { public static void main(String arg[]) { try { int a[] =new int[6]; for(int i = 0; i<7; i++) { a[i]=i; } } catch(Exception e) { System.out.println("Exception:"+e); } } } OUTPUT: cd C:\Program Files\Java\jdk1.6.0_26\bin javac NewClass1.java java NewClass1 Exception:java.Lang.ArrayIndexOutOfBoundsException: 6

You might also like