2. Exception Handling in Java Types of Errors 1.Compile time All syntax errors identified by java compiler. No class file is created when this occurs. So it is necessary to fix all compile time errors for successful compilation. Egs: Missing of semicolon, use of = instead of ==
3. Exception Handling in Java 2.Run time Some pgms may not run successfully due to wrong logic or errors like stack overflow. Some of the Common run time errors are: Division by 0 Array index out of bounds Negative array size etc..
4.
5.
6. Exception Handling in Java This mechanism consists of : 1. Find the problem(Hit the Exception) 2. Inform that an error has occurred(Throw the Exception) 3. Receive the error Information(Catch the Exception) 4. Take corrective actions(Handle the Exception)
10. Exception Handling in Java Java’s unchecked RuntimeException subclasses defined in java.lang Exception Meaning ArithmeticException Arithmetic error, such as divide-by-zero ArrayIndexOutOfBoundsException Array index is out-of-bounds ArrayStoreException Assignment to an array element of an incompatible type ClassCastException Invalid cast EnumConstantNotPresentException An attempt is made to use an undefined enumeration value IllegalArgumentException Illegal argument used to invoke a method IllegalMonitorStateException Illegal monitor operation, such as waiting on an unlocked thread IllegalStateException Environment or application is in incorrect state IllegalThreadStateException Requested operation not compatible with current thread state IndexOutOfBoundsException Some type of index is out-of-bounds NegativeArraySizeException Array created with a negative size
11. Exception Handling in Java Exception Meaning NullPointerException Invalid use of a null reference NumberFormatException Invalid conversion of a string to a numeric format SecurityException Attempt to violate security StringIndexOutOfBoundsException Attempt to index outside the bounds of a string TypeNotPresentException Type not fount UnsupportedOperationException An unsupported operation was encountered
12. Exception Handling in Java Java’s checked Exception defined in java.lang Exception Meaning ClassNotFoundException Class not found CloneNotSupportedException Attempt to clone an object that does not implement the Cloneable interface IllegalAccessException Access to a class is denied InstantiationException Attempt to create an object of an abstract class or interface InterruptedException One thread has been interrupted by another thread NoSuchFieldException A requested field does not exist NoSuchMethodException A requested method does not exist
13. Exception Handling in Java class Ex{ public static void main(String args[]){ int a=0; int b=2/a; } } Java.lang.ArithmeticException: / by zero at Ex.main
14. Exception Handling in Java try & catch try Block Statement that causes Exception Catch Block Statement that causes Exception
16. Exception Handling in Java class Ex{ public static void main(String args[]){ int d,a; try{ d=0; a=10/d; System.out.println("from try"); }catch(ArithmeticException e) { System.out.println("divsn by Zero"); } System.out.println("after catch"); } } Once an exception is thrown , program control transfers out of the try block into the catch block. Once the catch statement is executed pgm control continues with the next line following the entire try/catch mechanism.
17. Exception Handling in Java We can display the description of an Exception in a println statement by simply passing the exception as an argument. catch(ArithmeticException ae){ System.out.println(“Exception:”+ae); } o/p Exception:java.lang.ArithmeticException: /by zero
18.
19.
20. Exception Handling in Java Multiple catch Statement some cases, more than one exception could be raised by a single piece of code. such cases we can specify two or more catch clauses, each catching a different type of exception. when an exception thrown, each catch statement is inspected in order, and the first one whose type matches that of the exception is executed. After 1 catch statement is executed, the others are bypassed and execution continues after the try/catch block.
21. Exception Handling in Java class Ex{ public static void main(String args[]){ int d,a,len; try{ len=args.length; a=10/len; int c[]={1}; c[10]=23; } catch(ArithmeticException e){ System.out.println("divsn by Zero"+e); } catch(ArrayIndexOutOfBoundsExcept ion ae){ System.out.println("Array index"+ae); } System.out.println("after catch"); } }
22. Exception Handling in Java In multiple catch statement exception subclasses must come before any of their superclasses. Because a catch statement that uses a superclass will catch exception of that type plus any of its subclasses. Thus a subclass would never be reached if it came after its superclass. Further java compiler produces an error unreachable code.
23. Exception Handling in Java Nested try statement try statement can be nested class Ex{ public static void main(String dd[]){ int d,a,len; try{ len=dd.length; a=10/len; System.out.println(a); try{ if(len==1) len=len/(len-len); if(len==2){ int c[]={1}; c[10]=23; } } catch(ArrayIndexOutOfBoundsExceptio n ae){ System.out.println("Array index"+ae); } } catch(ArithmeticException e){ e.printStackTrace(); } } System.out.println("after catch"); } }
24.
25. Exception Handling in Java throw It is possible to throw an exception explicitly. Syntax: throw ThrowableInstance throwableInstance must b an object of type Throwable or a subclass of Throwable. By two ways we can obtain a Throwable object 1. Using parameter into a catch clause 2. Creating one with new operator
26. Exception Handling in Java class throwDemo{ public static void main(String args[]){ int size; int arry[]=new int[3]; size=Integer.parseInt(args[0]); try{ if(size<=0)throw new NegativeArraySizeException("Illegal Array size"); for(int i=0;i<3;i++) arry[i]+=i+1; }catch(NegativeArraySizeException e){ System.out.println(e); throw e; //rethrow the exception } } }
27.
28. Exception Handling in Java throws If a method causing an exception that it doesn't handle, it must specify this behavior that callers of the method can protect themselves against the exception. This can be done by using throws clause. throws clause lists the types of exception that a method might throw. Form type methodname(parameter list) throws Exception list {//body of method}
29. Exception Handling in Java import java.io.*; class ThrowsDemo{ public static void main(String args[]) throws IOException,NumberFormatException{ int i; InputStreamReader is=new InputStreamReader(System.in); BufferedReader br=new BufferedReader(in); i=Integer.parseInt(br.readLine()); System.out.println (i); }}
32. Exception Handling in Java Creating our own Exception class For creating an exception class our own simply make our class as subclass of the super class Exception. Eg: class MyException extends Exception { MyException (String msg){ super(msg); } }
33. Exception Handling in Java class TestMyException{ public static void main(String args[]){ int x=5,y=1000; try{ float z=(float)x/(float)y; if(z<0.01){ throw new MyException("too small number"); } }catch(MyException me){ System.out.println("caught my exception"); System.out.println(me.getMessage()); } finally{ System.out.println("from finally"); } } }