Java Tutorial - Java Exception








An exception is an abnormal condition that arises in a code sequence at run time. For example, read a non-existing file.

A Java exception is an object that describes an exceptional condition that has occurred in a piece of code.

Keywords

Java exception handling is managed via five keywords: try, catch, throw, throws, and finally.

try block has program statements that you want to monitor for exceptions.

If an exception occurs within the try block, it is thrown.

The catch statement can catch exception and handle it in rational manner.

To manually throw an exception, use the keyword throw.

Any exception that is thrown out of a method must be specified as such by a throws clause.

Any code that absolutely must be executed after a try block completes is put in a finally block.





Syntax

To handle an exception we put code which might have exceptions in a try...catch statement.

try { 
// block of code to monitor for errors 
} 
catch (ExceptionType1 exOb) { 
// exception handler for ExceptionType1 
}
catch (ExceptionType2 exOb) { 
// exception handler for ExceptionType2 
}

Program statements that might have exceptions are contained within a try block. The exception handler is coded using catch statement

Here, ExceptionType is the type of exception that has occurred.





Example

Enclose the code that you want to monitor inside a try block and catch clause.

The following program includes a try block and a catch clause that processes the ArithmeticException generated by the division-by-zero error:

public class Main {
  public static void main(String args[]) {
    int d, a;//from w w w .j a v  a2s  .com
    try { // monitor a block of code.
      d = 0;
      a = 42 / d;
      System.out.println("This will not be printed.");
    } catch (ArithmeticException e) { // catch divide-by-zero error
      System.out.println("Division by zero.");
    }
    System.out.println("After catch statement.");
  }
}

This program generates the following output:

Example 2

Once an exception is thrown, program control transfers out of the try block into the catch block. Execution never returns to the try block from a catch.

The following code handles an exception and move on.

import java.util.Random;
/*w w w  .  j a va 2s. co  m*/
public class Main {
  public static void main(String args[]) {
    int a = 0, b = 0, c = 0;
    Random r = new Random();
    for (int i = 0; i < 32000; i++) {
      try {
        b = r.nextInt();
        c = r.nextInt();
        a = 12345 / (b / c);
      } catch (ArithmeticException e) {
        System.out.println("Division by zero.");
        a = 0; // set a to zero and continue
      }
      System.out.println("a: " + a);
    }
  }
}

The code above generates the following result.