TwitterFacebookGoogle PlusLinkedInRSS FeedEmail

Wednesday, November 28, 2012

Exception handling in Java

Exception:

                 The term "exception"  means "exceptional condition" and is a problem that arises during the execution of a program. A bunch of things can lead to exceptions, including hardware failures, programmer error, file that needs to be opened cannot be found, resource exhaustion. When an exceptional events occurs in java an exception is said to be "thrown". The code that's responsible for doing something about the exception is called an "exception handler". 

Exception Hierarchy



Exception is categorized into three category

Checked Exception:

                          Exception that cannot be predicated by the programmer. These type of exception must be checked. For example file that needs to be opened cannot be found.

Runtime exceptions:

                        Unlike checked exceptions, runtime exceptions are ignored at the time of compliation.

Errors:

                        Errors are typically ignored in your code because you can rarely do anything about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation.

Exception Handling:

                        In Java, Exception handling is done using five keywords try,catch,throw,throws and finally. Exceptions handling works by transferring the execution of a program to an appropriate exception handler when exception occurs.

Using try and catch:

                         The try is used to define a block of code in which exception may occur. This block of code is called guarded region. A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs in guarded code, the catch block (or blocks) that follows the try is checked. If the type of exception that occurred is listed in a catch block, the exception is passed to the catch block much as an argument is passed into a method parameter. 
         try{
            //put code that might cause exception here 
               }
           catch(ExceptionName e)
           { //put code that handle exception }

Multiple catch Blocks:

                         A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks like the following:

try
{
   //Protected code
}catch(ExceptionType1 e1)
{
   //Catch block
}catch(ExceptionType2 e2)
{
   //Catch block
}
                  You can have any number of catch block after a single try. If an exception occurs in the guarded code, the exception is thrown to the first catch block in the list. If the exception type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes down to the second catch statement. This continues until the exception either is caught or falls through all catches.

throws/throw Keywords:

                            throw keyword is used to throw an exception explicitly. The general form of throw is

      throw ThrowableInstance;

ThrowableInstance must be an object of type Throwable classes, such as String and Object cannot be used as Exception.
                             If a method does not handle a checked exception, the method must declare it using the throws keyword. The throws keyword appears at the end of a method's signature.The general form of throws clause is

      type method-name(parameter-list) throws exception-list

example:

The following method declares that it throws a ArithmeticException:
import java.io.*;
public class testExcetion
{
   public void average(int sum) throws ArithmeticException
   {
       // some code
      // throwing exception explicitly
      throw new ArithmeticException();
   }
   
}

finally clause:

              A finally block of code always executes, whether or not an exception has occurred.Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter what happens in the protected code. A finally block appears at the end of the catch blocks and has the following syntax:

try
{
   //Protected code
}catch(ExceptionType1 e1)
{
   //Catch block
}catch(ExceptionType2 e2)
{
   //Catch block
}catch(ExceptionType3 e3)
{
   //Catch block
}finally
{
   //The finally block always executes.
}

example:

import java.io.*;

class readfromfile
{
public static void main(String ar[])
{
File file=new File("d:\\myfile.txt");
FileInputStream fis=null;
BufferedInputStream bis = null;
DataInputStream dis = null;

try{
fis=new FileInputStream(file);
 bis=new BufferedInputStream(fis); 
dis=new DataInputStream(bis);


while(dis.available()!=0)
{
 System.out.println(dis.readLine());
}
}catch(IOException ex)
{System.out.println("Exception");}

//finally block 
finally{
try{
fis.close();
bis.close();
dis.close();
}
catch(IOException e)
{System.out.println("Input Exception");}
}
}


0 comments: