Sunday, 10 January 2016

Exception Handling in Java

Exception Handling in java is the powerful mechanism to handle run time errors in a java program.It is an abnormal condition in a program running cycle. 

Mainly Exceptions are of checked and unchecked exceptions.

Advantages of Exceptions handling:

statement1;
statement2;
statement3; // Exception occurs
statement4;

Then the fourth statement will not execute, instead if we handled the exception then the next statement will execute.

Types of exceptions:

As mentioned above there are two types of exceptions:
Checked and Unchecked Exceptions

Checked Exceptions:
The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions e.g.IOException, SQLException etc. Checked exceptions are checked at compile-time.

Unchecked Exceptions:
The classes that extend RuntimeException are known as unchecked exceptions e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at compile-time rather they are checked at runtime. 

Common Scenarios for exceptions:

  1. int n=20/0;//ArithmeticException  
  2. String a=null;  System.out.println(a.length()); //NullPointerException  
  3. String a="one";  int i=Integer.parseInt(a);//NumberFormatException  
  4. int a[]=new int[5];  a[10]=50//ArrayIndexOutOfBoundsException 
Implementing exceptions:
Java try-catch and Java try-finally blocks

Syntax of try- catch
  1. try{  
  2. //code that may throw exception  
  3. }
  4. catch(Exception_class_Name ref){
  5. }  
Syntax of try-finally block
  1. try{  
  2. //code that may throw exception  
  3. }finally{}  

Example1:

public class sample{
  public static void main(String args[]){
   try{
      int n=20/0;
   }catch(ArithmeticException e){System.out.println(e);}
   System.out.println("rest of the code...");
}

Example2:

class sample2{
  public static void main(String args[]){
  try{
   int n=45/5;
   System.out.println(n);
  }
  catch(NullPointerException e){System.out.println(e);}
  finally{System.out.println("finally block is always executed");}
  System.out.println("rest of the code...");
  }
}  

Above mentioned above will give an idea on what is exceptions and exception handling in java.

No comments :

Post a Comment