What are Java predefined class type for exception handing

Exception Classes

The following diagram shows the Java exception type hierarchy:

Exception and its subclasses are used for exceptional conditions that user programs should catch. You can subclass Exception to create your own custom exception types.

Error defines exceptions that are not expected to be caught under normal circumstances. Java run-time system use Error to indicate errors in the run-time environment. Stack overflow is an example of such an error.

Uncaught Exceptions

This small program includes an expression that intentionally causes a divide-by-zero error:


public class Main {
  public static void main(String args[]) {
    int d = 0;/* www. j  a v a2s.c o  m*/
    int a = 42 / d;
  }
}

Here is the exception generated when this example is executed:

Here is another version of the preceding program that introduces the same error but in a method separate from main( ):


public class Main {
  static void subroutine() {
    int d = 0;/* ww w  .j av  a2 s  .c o  m*/
    int a = 10 / d;
  }

  public static void main(String args[]) {
    subroutine();
  }
}

The resulting stack trace from the default exception handler shows how the entire call stack is displayed:

Example

You can display exception description message in a println( ) statement.

For example, the catch block can be written like this:


import java.util.Random;
//  w  w w.  j a  v  a  2s .c  om
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("Exception: " + e); 
        a = 0; // set a to zero and continue
      }
      System.out.println("a: " + a);
    }
  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    Java Language »




Java Data Type, Operator
Java Statement
Java Class
Java Array
Java Exception Handling
Java Annotations
Java Generics
Java Data Structures