Wednesday, 5 August 2015

Exception Class in Java Programming Language

What is Exception

Exception is raised due to abnormal condition which interrupts the normal flow of the program Exception is a class in java Programming language and exception raised at runtime is the object of Exception class or Exception class Hierarchy.


All the Exception needs to be handled by taking the appropriate actions by the programmer.

Exception handlers are also provided by the jvm even if the programmers don’t provide the handlers.


There are 5 keywords used in java exception handling.
1. try
2. catch
3. finally
4. throw

5. throws


Try
1. Try is a block which has to be written in a method block.
2. Try can have single or multiple statements.
3. Try can have any number of Exceptions  but try block will raise only  one Exception at a time .
4. Try block can be followed by single catch or multiple catch to handle the Exception or it  can also be followed by finally block
5. But there cannot be any statements between any of these blocks .  

Syntax of java try-catch
try{  
//code that may throw exception  
}catch(Exception_class_Name ref){}  

Syntax of try-finally block
try{  
//code that may throw exception  
}finally{}  

Java catch block
Java catch block is used to handle the Exception raised by try block. It must be used after the try block only. One try can have one catch or any number of catches but they should  be  continues.


Java finally  block

Finally is a block that contain a set of statements which will be executed either the exception are handled properly or not or not.

Finally block can be followed after the catch block or it can be after try block but not between try and catch blocks. There cannot be multiple finally blocks 

try{......}
finally{.....}
(or)
try{.......}
catch(Exception e){.....}
finally{.....}

Example Program 

public class Testtrycatch2
{  
  public static void main(String args[])
{  
   Try
{  
      int data=50/0;  
     }
       catch(ArithmeticException e)
      {
        System.out.println(e);
      }  
     finally
    {
   
 System.out.println("rest of the code...");  

}  }

---------------------------------------------------------------------
Article By:
K.Pavan Kumar
CSE Dept
Assistant Professor
Sphoorthy Engineering College

Sphoorthy Engineering College





No comments:

Post a Comment