Exception



What is an Exception?

Exception is a condition due to which our program terminates abnormally.Exception causes our program to crash.

Definition: An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.


What is Exception Handling?

Exception handling is a mechanism used to describe what to do when something unexcepted happen.

For example:

  • When a method is invoked with unacceptable arguments.
  • When a network connection fails.
  • When the user asks to open a non-existent file.

Catagories Of Exception ?

The Java programming language provides two broad categories of exceptions:

  • Checked
  • Unchecked

Checked exceptions are those that the programmer is expected to handle in the program, and that arise from external conditions that can readily occur in a working program.

Unchecked exceptions might arise from conditions that represent bugs, or situations that are considered generally too difficult for a program to handle reasonably. Exceptions that arise from a category of situations that probably represent bugs are called runtime exceptions.

Let us understand the concept of exception by using the example.

1 public class AddArguments { 2 public static void main(String args[]) { 3 int sum = 0; 4 for ( int i = 0; i < args.length; i++ ) { 5 sum += Integer.parseInt(args[i]); 6 } 7 System.out.println("Sum = " + sum); 8 } 9 } Condition 1: java AddArguments 1 2 3 4 Sum = 10

Condition 2: This program fails if any of the arguments are not integers: java AddArguments 1 two 3.0 4
Exception in thread "main" java.lang.NumberFormatException: For input string: "two"at java.lang.NumberFormatException.forInputString(NumberFormat Exception.java:48) at java.lang.Integer.parseInt(Integer.java:447) at java.lang.Integer.parseInt(Integer.java:497) at AddArguments.main(AddArguments.java:5)

Constructs For Handling Exception

  • try
  • catch
  • finally
  • throw
  • throws

Points To Remember

  • A program can catch exceptions by using a combination of the try, catch, and finally blocks.
  • The try block identifies a block of code in which an exception can occur.
  • The catch block identifies a block of code, known as an exception handler, that can handle a particular type of exception.
  • The finally block identifies a block of code that is guaranteed to execute, and is the right place to close files, recover resources, and otherwise clean up after the code enclosed in the try block.
  • The try statement should contain at least one catch block or a finally block and may have multiple catch blocks.

Type 1.
	try
	{
		------->try block is a block 
         		where exception might arrise	
	}
	catch(Exception e)	
	{
		------->catch block is a block 
                 	where exception is handled
	}
Type 2. 
	try
	{
	
	}
	catch(ArithmaticException ae)
	{
	
	}
	catch(IOException ioe)
	{
	
	}
	catch(Exception e)
	{
	
	}
Type 3.
	try
	{
	
	}
	catch(Exception e)
	{
	
	}
	finally
	{    ------->finally block executes 
       		wheather exception occur or not.

	}

  • A try block can't be used alone . It must be paired with catch or finally
  • catch and finally can't be paired without try.
  • A try block must have at least one catch block that follows it immediately.
  • The catch statement takes the object of the exception class that refers to the exception caught, as a parameter.
  • Once the exception is caught, the statements within the catch block are executed.
  • The scope of the catch block is restricted to the statements in the preceding try block only.


Call Stack Mechanism

  • If an exception is not handled in the current try-catch block, it is thrown to the caller of the method.
  • If the exception gets back to the main method and is not handled there, the program is terminated abnormally.



try-catch Example



import java.io.*;
public class ExcepTest
{

   public static void main(String args[]){
      try{
         int a[] = new int[2];
         System.out.println("Access element three :" + a[3]);
      }catch(ArrayIndexOutOfBoundsException e){
         System.out.println("Exception thrown  :" + e);
      }
      System.out.println("Out of the block");
   }
}

Finally Clause

The finally clause defines a block of code that always executes, regardless of whether an exception is thrown.

try-catch-finally Example



public class ExcepTest
{

   public static void main(String args[])
  {
      int a[] = new int[2];

      try{
         System.out.println("Access element three :" + a[3]);
      	 }

	catch(ArrayIndexOutOfBoundsException e)
	 {
         System.out.println("Exception thrown  :" + e);
         }

        finally
	 {
         a[0] = 6;
         System.out.println("First element value: " +a[0]);
         System.out.println("The finally statement is executed");
         }
   }
}

Points To Remember

  • A catch clause cannot exist without a try statement.
  • It is not compulsory to have finally clauses when ever a try/catch block is present.
  • The try block cannot be present without either catch clause or finally clause.
  • Any code cannot be present in between the try, catch, finally blocks.