Exception handling In java

The process of converting system error messages into user friendly error message is known as Exception handling. This is one of the powerful feature of Java to handle run time error and maintain normal flow of java application.

Exception

An Exception is an event, which occurs during the execution of a program that disrupts the normal flow of the program’s Instructions.

Why use Exception Handling

Handling the exception is nothing but converting system error generated message into user friendly error message in others word whenever an exception occurs in the java application, JVM will create an object of appropriate exception of sub class and generates system error message, these system generated messages are not understandable by user so need to convert it into user-friendly error message. You can convert system error message into user-friendly error message by using exception handling feature of java.

Use five keywords for Handling the Exception

  • try
  • catch
  • finally
  • throws
  • throw

Syntax for handling the exception

Syntax

try

{

  // statements causes problem at run time

}

catch(type of exception-1 object-1)

{

  // statements provides user friendly error message

}

catch(type of exception-2 object-2)

{

  // statements provides user friendly error message

}

finally

{

  // statements which will execute compulsory

}

Example without Exception Handling

Syntax

class ExceptionDemo

{

public static void main(String[] args)

{

int a=10, ans=0;

ans=a/0;

System.out.println("Denominator not be zero");                             

}

}

Abnormally terminate program and give a message like below, this error message is not understandable by user so we convert this error message into user friendly error message, like “denominator not be zero”.

Example of Exception Handling

Example

class ExceptionDemo

{

public static void main(String[] args)

{

int a=10, ans=0;

try

{

ans=a/0;

}

catch (Exception e)

{

System.out.println("Denominator not be zero");

}           

}

}

Output

Denominator not be zero

try block

Inside try block we write the block of statements which causes executions at run time in other words try block always contains problematic statements.

Important points about try block

·         If any exception occurs in try block then CPU controls comes out to the try block and executes appropriate catch block.

·         After executing appropriate catch block, even though we use run time statement, CPU control never goes to try block to execute the rest of the statements.

·         Each and every try block must be immediately followed by catch block that is no intermediate statements are allowed between try and catch block.

Syntax

try

{

  .....

}

/* Here no other statements are allowed

between try and catch block */

catch()

{

  ....

}

  • Each and every try block must contains at least one catch block. But it is highly recommended to write multiple catch blocks for generating multiple user friendly error messages.
  • One try block can contains another try block that is nested or inner try block can be possible.

Syntax

try

{

.......

try

{

.......

}

}

catch block

Inside catch block we write the block of statements which will generates user friendly error messages.

Catch block important points

  • Catch block will execute exception occurs in try block.
  • You can write multiple catch blocks for generating multiple user friendly error messages to make your application strong. You can see below example.
  • At a time only one catch block will execute out of multiple catch blocks.
  • In catch block you declare an object of sub class and it will be internally referenced by JVM.

Example without Exception Handling

Example

class ExceptionDemo

{

public static void main(String[] args)

{

int a=10, ans=0;

ans=a/0;

System.out.println("Denominator not be zero");                             

}

}

Abnormally terminate program and give a message like below, this error message is not understandable by user so we convert this error message into user friendly error message, like “denominator not be zero”.

 

Example of Exception Handling

Example

class ExceptionDemo

{

public static void main(String[] args)

{

int a=10, ans=0;

try

{

ans=a/0;

}

catch (Exception e)

{

System.out.println("Denominator not be zero");

}           

}

}

Output

Denominator not be zero

Multiple catch block

You can write multiple catch blocks for generating multiple user friendly error messages to make your application strong. You can see below example.

Example

import java.util.*;

class ExceptionDemo 

{

public static void main(String[] args) 

{

int a, b, ans=0;

Scanner s=new Scanner(System.in);

System.out.println("Enter any two numbers: ");

try

{

             a=s.nextInt();

             b=s.nextInt();

             ans=a/b;

             System.out.println("Result: "+ans);

}

catch(ArithmeticException ae)

{

System.out.println("Denominator not be zero");

}            

catch(Exception e)

{

System.out.println("Enter valid number");

}            

}

}

Output

Enter any two number: 5 0

Denominator not be zero

 

 

Difference between throw and throws.

  throw throws
1. Java throw keyword is used to explicitly throw an exception. Java throws keyword is used to declare an exception.
2. Checked exception cannot be propagated using throw only. Checked exception can be propagated with throws.
3. Throw is followed by an instance. Throws is followed by class.
4. Throw is used within the method. Throws is used with the method signature.
5. You cannot throw multiple exceptions. You can declare multiple exceptions e.g.
public void method()throws IOException,SQLException.

 

Finally block

It is a block that is used to execute important code such as closing connection, stream etc.

Java finally block is always executed whether exception is handled or not.

Java finally block must be followed by try or catch block.

Why use java finally

  • Finally block in java can be used to put “cleanup” code such as closing a file, closing connection etc.

Usage of Java finally

class TestFinallyBlock{  

  public static void main(String args[]){  

  try{  

   int data=25/5;  

   System.out.println(data);  

  }  

  catch(NullPointerException e){System.out.println(e);}  

  finally{

   System.out.println("finally block");

    }  

  System.out.println("rest of the code");  

  }  

}  

Output:5
       finally block
       rest of the code

Way to skip finally block

public class Main {
    public static void main(String[] args) {
        try {
            System.out.println("Hi");

            System.exit(0);
        }
        finally {
            System.out.println("Bye!");
        }
    }
}

In the above code by calling system.exit in try block terminates the JVM due to wich finally block will not be executed.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s