Anda di halaman 1dari 10

EXCEPTION HANDLING

An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. Exceptions come in two flavors: checked and unchecked. Checked exceptions are types of exceptions which are beyond the control of programs.say I/O exception RemoteException.This could happen when the resource you were looking was not found(e.g file missing or remote server is down) Checked Exceptions : 1)Indicate most conditions that a reasonable application might want to catch 2) throws clause checked by the compiler. 3)Not subclass of RuntimeException. Unchecked exceptions are Runtime excpetions which happens due to programmatic errors wrong data etc. Javas Checked Exceptions in java.lang ClassNotFoundException CloneNotSupportedException IllegalAccessException InstantiationException InterruptedException NoSuchFieldException NoSuchMethodException

Unchecked Exceptions: 1)Indicate serious problem that a reasonable application should not try to catch and exceptions that can be thrown during the normal operation of the JVM. 2)Not checked by the compiler. 3)subclass of RuntimeException Class.

Javas Unchecked RuntimeException Subclasses ArithmeticException ArrayIndexOutOfBoundsException ArraStoreException ClassCastException IllegalArgumentException IllegalMonitorStateException IllegalStateException IllegalThreadStateException IndexOutOfBoundsException NegativeArraySizeException NullPointerException NumberFormatException SecurityException StringIndexOutOfBounds UnsupportedOperationException

Exceptions can be handled by using 2 core blocks namely try and catch. The try block encloses some code which might throw an exception (i.e. generate an error). The catch block contains the error handling code, i.e. determines what should be done if an error is detected If an exception is thrown in the try block, execution control jumps to the catch block and then executes linearly.

Finally block: It is ideally used for closing the resources such as file handlers or database connections acquired during the execution of the method. The finally block executes irrespective of an exception being thrown or not. The only situation when finally will not be executed is when the JVM shuts down.

Certain Rules to be followed: - We can have a single try with multi catch blocks. - Syntax can be - try...catch....finally / try...finally. - We can have nested try...catch blocks. - Regardless of whether or not an exception occurred or whether or not it was handled, if there is a finally block, itll be executed always. However, there can be only one finally block per try block.

throws Clause The throws clause lists the types of exceptions that a method might throw

throw Statement A program can explicitly throw an exception using the throw statement. When an exception is thrown, runtime system searches for a catch block to handle the exception.

User Defined Exceptions When the Exceptions provided by the Java API does not fulfill our needs, we can create our own Exception Classes. All user defined exception classes should inherit Exception Class or Throwable Class.

Nested try block There may be situations when the code in our try block throws exceptions at more than one instance. It may also happen that the code in the catch or finally block itself throws an exception. For such an undesirable situation java provides us nested try-catch or try-catch-finally or try-finally blocks.

Programs explaining Exception Handling

1. Exception public class Exceptn { public static void main(String[] args) { int a=10,b=0,c=0; c=a/b; System.out.println("Result is:"+c); } }

Output: Exception in thread "main" java.lang.ArithmeticException: / by zero at exception.Exceptn.main(Exceptn.java:16) Java Result: 1 2. Try-Catch public class Exception1 { public static void main(String[] args) { int a=10,b=0,c; try { c=a/b; } catch(ArithmeticException ae) { System.out.println(ae); b=2;

c=a/b; } System.out.println("Result is:"+c); } }

Output: java.lang.ArithmeticException: / by zero Result is:5

3. Multiple Catch public class TryCatch { public static void main(String args[]) { int array[]={0,0}; int num1,num2,result=0; num1=100; num2=0; try { result=num1/num2; System.out.println(num1/array[2]); } catch(ArithmeticException e) { System.out.println("Division by zero"); } catch(ArrayIndexOutOfBoundsException e)

{ System.out.println("Index out of bounds"); } catch(Exception e) { System.out.println("error"); } System.out.println("The result is: "+result); } } Output: Division by zero The result is: 0 -----------------------------------------------------------------------------------------------------------------------------------------

4. Finally clause public class Finally{ public static void main(String args[]) { try { System.out.println("Try block before the error"); System.out.println(1/0); System.out.println("Try block after the error"); } catch(ArithmeticException e) { System.out.println("Catch block"); System.out.println("A stack trace of the error:"); e.printStackTrace();

System.out.println("The operation is not possible"); } finally { System.out.println("Finally Block"); } } }

Output: Try block before the error Catch block A stack trace of the error: java.lang.ArithmeticException: / by zero at Finally.main(Finally.java:7) The operation is not possible Finally Block

5. Throw Statement class ThrowDemo { public static void main(String args[]) { try { // throw keyword is used to raise an exception by the user throw new NullPointerException("Throwing an exception explicitly"); } catch(NullPointerException e) { System.out.println("Exception raised is: " + e); } }

Output: Exception raised is: java.lang.NullPointerException: Throwing an exception explicitly

6. Nested try-catch public class NestedTry { public void execute(){ try{ try{ for(int i=0;i<100;i++){ System.out.println(i); if(i==5){ throw new java.io.IOException(); } } }catch(NumberFormatException nfe){ System.out.println("Caught in inner block"); } }catch(Exception e){ System.out.println("Caught in outer block"); } } public static void main(String args[]){ NestedTry n=new NestedTry(); n.execute(); }

Output: 0 1 2 3 4 5 Caught in outer block

7. throws keyword, User Defined Exception class MyException extends Exception{ public MyException(String msg){ super(msg); } } public class Test{ static int divide(int first, int second) throws MyException{ if(second==0) throw new MyException("Cannot divide by zero"); return first/second; } public static void main(String args[]){ try{ System.out.println(divide(4,0)); } catch(MyException exc){

exc.printStackTrace(); } } }

Output: MyException: Cannot divide by zero at Test.divide(Test.java:9) at Test.main(Test.java:14)

Anda mungkin juga menyukai