Exception Handling in JAVA


Introduction

You learn that there are three categories of errors : Syntax error, Runtime error and Logic error. A Syntax error arises because a rule of the language has not been followed; they are detected by the compiler. Runtime errors occur while the program is running, if the environment detects an operation that is impossible to carry out. A logic error occurs when the program does not perform the way it was intended to. 
An exception is one of the abnormal conditions that can occur during the execution of a program. Exceptions are handled using an API which is given in java.lang package in the form of various Exception classes.

exceptFig1.gif

An exception can occur for many reasons; some of the general reasons are the following:

  1. A user has entered invalid data .
  2. A file needs to be opened but cannot be found.
  3. A network connection failed in the middle of communication

Catching an Exception

To catch an Exception in Java you need to use a try block with one or more catch clauses. In each catch clause you can define one specific type of exception that it is prepared to handle. You can put all the code in a try block that can potentially cause an exception to be generated.

Syntax

try{

// code that may cause of Exception

    }catch(......)
     {
    //Code of handle the exception
    }
Note-you can have more than one catch block for a single try

Syntax

try{

// code that may cause of Exception

}catch(......)//1
{
//Code of handle the exception
}

catch(...2...)//2
{
//Code of handle the exception
}

Example

class MultipleCatch
 {
  public static void main(String arg[])
         {
            int a,x;
            try{
                a = Integer.parseInt(arg[0]); // NumberFormat + ArrayIndex
                x = 100 / a; // ArithmeticException
                System.out.println("x = "+x);
                }catch(ArithmeticException ex) // only for ArithmeticException
                        {
                     System.out.println("Ohh! sorry , this is / by 0 ");
                        }
                  catch(NumberFormatException ex) // only for NumberFormatException
                        {
                     System.out.println("invalid number for type casting , these alphabet");
                        }
                  catch(ArrayIndexOutOfBoundsException ex)  // only for ArrayIndexOutOfBoundsException
                      {
                    System.out.println("sorry there is no command line arguments");
                       }
           System.out.println("Thanxxxxxxxxxxxxxxxxxxx");
         }
 }

OUTPUT

multiplecatch.gif
 

Throwing  exception

To throw an exception you simply use the throw with an object reference. All the methods use the throw statement to throw an exception.

Syntax

throw someThrowableObject ;

Example

class UseThrow
        {
        public static void main(String arg[])
            {
                int c=0;
                int a=Integer.parseInt(arg[0]);
                int b=Integer.parseInt(arg[1]);
                UseThrow ut=new UseThrow();
                try{
                    c=a/b;
                    throw new ArithmeticException();
                    }catch (Exception e)
                            {
                        System.out.println(e);
                            }
                System.out.println("the division = "+c);
            }
       }

OUTPUT

Usethrow.gif

Use of throws key word

throws is keyword that is defined in Java. It is used for indicating that a particular method is throwing a particular type of exception while this method is in execution. When we use a throws clause in any method then it is the responsibility of the caller method which handle this exception with the help of putting it in try catch block.

Syntax

punlic int div(int a, int b) throws AirthmeticException
{
// body of methods
}

Example

class MyThrows
{
    public void div() throws ArithmeticException
        {
        int a=1,b=0,c;
        c=a/b;
        System.out.println("now you are fine");
        }
   public static void main(String arg[])
        {
        MyThrows mt=new MyThrows();
        try{
            mt.div();
            }catch(Exception e)
                    {
                    System.out.println(e);
                    }
        }
}

OUTPUT

Mythrows.gif

Use of finally keyword

A finally block always executes when the try block exits. A finally block is used for whatever necessary code is needed, such as termination of a connection returning some value etc.

Syntax

try{
  // code that may cause of Exception
  
}finally{
        //Code  that is always  execute
             }

Syntax finally keyword with catch clause

try{
// code that may cause of Exception
   
}catch(......)
        {
     //Code of handle the exception
        }
     finally
        {
     //Code  that is always  execute
       
}

Example

class Finally

{
  static int div(int a,int b)
    {
    return a/b;
    } 
  public static void main(String ar[])
    {
     try{
           System.out.println(+div(4,5));
             }
    catch(Exception e)
            {
            System.out.println("Exception in main:"+e);
            }
    finally
        {
        System.out.println("I am always excute because we are in finally block");
        }
   }
}

OUTPUT

finally.gif

Resource

Exception Handling in Visual COBOL.NET

Custom Exception Handling in C#

Exception Handling and .NET

Exception Handling

Guide to Improving Code Performance in .NET: Part II


Up Next
    Ebook Download
    View all
    Learn
    View all