Exception Handling in java

What is an Exception


The exception is an unwanted, unexpected event that disturbs the normal flow of the program. An exception is an object which is thrown at runtime by JVM.


public class Test {
       public static void main(String[] args) {
              System.out.println("statement one");
              System.out.println("statement two");
              int i=10/0;
              System.out.println("statement three");
              System.out.println("statement four");
       }
}


Output:



statement one
statement two
Exception in thread "main" java.lang.ArithmeticException: / by zero



In the above example, statement one&two are executed normally but statement three&four didn’t execute because the division of 10 by zero will give an undefined result so that JVM will terminate the program abnormally and rest of program didn’t execute.


Exception Handling


The main objective of the Exception handling provides the alternative solution to continue the rest of the program normally.


package com.exceptions;
public class Test {
       public static void main(String[] args) {
              System.out.println("statement one");
              System.out.println("statement two");
              try{
                 int i=10/0; // get the exception
                 System.out.println("iam in try : "+i);
              }
              catch(ArithmeticException ae){                                      
                 System.out.println("Don't divide by zero "+ae);//alternative solution
              }
              System.out.println("statement three");
              System.out.println("statement four");
       }
}


Output:



statement one
statement two
Don't divide by zero java.lang.ArithmeticException: / by zero
statement three
statement four


The above program executed normally because of handled exception by using try catch blocks. Write the risky code in try block where we have the choice to get the exception.

If any exception occurred in try block then alternatively execute the catch block to continue the rest of the program normally as shown in the above program.



This way of alternative solution is exception handling.


No comments:

Post a Comment