• An exception is an abnormal condition that arises in a code at run time.
  • In other words, an exception is a run-time error.
  • An exception object describes a problem encountered during the execution of a program.
  • Some of the exceptions are integer division-by-zero, array index negative or out-of-bounds, illegal cast, interrupted I/O operation, unexpected end-of-file condition, missing file, incorrect number format etc.
  • Errors must be checked and handled manually in the languages that do not support exception handling.
  • When an exceptional condition arises, an object representing that exception is created and thrown in the method that caused the error. That method may choose to handle the exception itself, or pass it on. Either way, at some point, the exception is caught and processed.
  • Java exception handling is managed via five keywords: try, catch, throw, throws and finally.
  1. Try:All program statements that might generate exceptions are placed within a try block to monitor. If an exception is generated t is thrown to the catch block.
  2. Catch:it contains code to handle exceptions generated within the try block.
  3. Throw: system-generated exceptions are automatically thrown by the Java run-time system. To manually throw an exception, use the keyword throw.
  4. Throws: any exception that is thrown out of a method must be specified by a throws clause.
  5. Finally:Any code that must be executed is put in a finally block.Statements of within the finally block will be executed compulsory in both normal and abnormal conditions.
General form:
try
{
  //block of code to monitor for errors…
}
catch(ExceptionTypeexObj)
{
  // exception handling block
}
finally
{
  // finally block
}
  • Statements that you want to monitor for exceptions are placed into the try block. If a problem occurs during its executing, an exception is thrown to the catch block.
  • Catch blocks contains code to handle specific exceptions.
  • We can also place multiple catch blocks to handle multiple type of exceptions.
  • An exception object is passed to each catch block as an argument. It contains information about the exception.
  • If a problem occurs during execution of the try block, the JVM immediately stops executing the try block and looks for a catch block that can process that type of exception.
  • Any remaining statements in the try block are not executed. The search begins at the first catch block. If the type of the exception object matches the type of the catch block parameter, those statements are executed. Otherwise, the remaining catch clauses are examined in sequence for a type match.
  • When a catch block completes executing, control passes to the statements in the finally block.
  • The finally block is executed in all circumstances.
  • The finally block is optional. However, in some applications it can provide a useful way to release resources. For example, closing a files or databases.
  • Each try block must have at least one catch or finally block.
class ExceptionTest
{
   public static void main(String args[])
   {
      int a=10;
      int b=0,x=0;
      try
      {
         x=a/b;
      }
      catch(ArithmeticException e)
      {
         System.out.println(“Division by zero” + e.toString());
      }
  }
}

Output:
Division by zero
  • We can display description of the exception using the exception object’s toString().
Multiple catch Clauses
  • In some cases, more than one exception could be generated by a single piece of code. To handle this type of situation, we can specify two or more catch clauses, each catching a different type of exception.
  • When an exception is thrown, each catch statement is inspected in order, and the first one whose type matches that of the exception is executed.
  • After one catch statement executes, the others are bypassed, and execution continues after the try/catch block.
  • The following example traps two different exception types:
Class MultiCatch
{
   	public static void main(String args[])
   	{
       	     try
	     {
          	int a=args.length;
          	System.out.println(“a=” +a);
          	int b= 42/a;
          	int c[]={1};
          	c[42]=99;
             }
       	     catch(ArithmeticException e)
       	     {
          	System.out.println(“divide by zero:” +e);
       	     }
       	     catch(ArrayIndexOutOfBoundsException ex)
       	     {
          	System.out.println(“Array index is out of bound:” +ex.toString());
       	     }
       	     catch(Exception exp)
       	     {
          	System.out.println(“Unknown Exception:” +exp.toString());
       	     }
  	}
        System.out.println(“After try/catch block”);
}
  • When multiple catch statements are used, exception sub-classes must come before any of their super-classes.
  • Because a catch statement that uses a super-class will catch exceptions of that type plus any of its sub-classes. So, a subclass would never be reached if it came after its super-class.
  • In java, unreachable code is also an error.
  • For example, in above program if we write catch bock of Exception object first before the ArithmeticExceptionand ArrayIndexOutOfBoundsException then it will be never executed because they are the sub classes of the Exception super class so Exception catch block will handle it.

Throw

  • It is also possible to explicitly generate an exception. This can be done with a throw statement. Its form is as follows:
		throw exceptionObject;
  • Here, object must be of type java.lang.Throwable. Otherwise, a compiler error occurs.
  • Inside a catch block, you may throw the same exception object that was provided as an argument. This can be done with the following syntax:
catch(ExceptionTypeparam)
{
   throw param;
}
  • We may also create and throw a new exception object as follows:
    • throw new exceptionType(args);
  • Here, exceptionType is the type of the exception object and args is the optional argument list for its constructor.
  • When a throw statement is encountered, a search for a matching catch block begins. Any subsequent statements in the same try or catch block are not executed.

Throws

  • When there is a possibility for a method to generate some exceptions that it can’t handle, it must be specify so that callers of that method can protect from such exceptions.
  • A throws keyword is used to specify list of such exceptions that a method cannot handle with its declaration
  • General form for such method declaration is as follow:
Type method-name(parameter-list) throwsexception-list
{
   // Method body
}

class demoThrows
{
   	Static void methodThrow() IllegalAccessException
   	{
       		System.out.println(“Inside methodThrow”);
       		Throw new IllegalAccessException(“demo”);
        }
   	public static void main(String args[])
   	{
      	    try
            {
           	methodThrow();
	    }
       	    catch(IllegalAccessException e)
       	    {
          	System.out.println(“Exception: ” +e);
       	    }
   	}
}