Java Tutorial - Java Exception Type








The following diagram shows the Java exception type hierarchy:

Throwable
 |
 |
 +---Exception. 
 |    |
 |    |
 |    +--- RuntimeException
 |
 +---Error

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;
    int a = 42 / d;
  }
}

Here is the exception generated when this example is executed:





Example

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;/*from w  w w .  j a  va2s .  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 2

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

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

import java.util.Random;
/*from  www  .ja va 2  s  .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("Exception: " + e); 
        a = 0; // set a to zero and continue
      }
      System.out.println("a: " + a);
    }
  }
}

The code above generates the following result.

What are Java's Built-in Exceptions

Exceptions subclassing RuntimeException need not be included in any method's throws list. These are called unchecked exceptions.

The unchecked exceptions defined in java.lang are listed in the following table.

ExceptionMeaning
ArithmeticExceptionArithmetic error, such as divide-by-zero.
ArrayIndexOutOfBoundsExceptionArray index is out-of-bounds.
ArrayStoreExceptionAssignment to an array element of an incompatible type.
ClassCastExceptionInvalid cast.
EnumConstantNotPresentExceptionAn attempt is made to use an undefined enumeration value.
IllegalArgumentExceptionIllegal argument used to invoke a method.
IllegalMonitorStateExceptionIllegal monitor operation, such as waiting on an unlocked thread.
IllegalStateExceptionEnvironment or application is in incorrect state.
IllegalThreadStateExceptionRequested operation not compatible with current thread state.
IndexOutOfBoundsExceptionSome type of index is out-of-bounds.
NegativeArraySizeExceptionArray created with a negative size.
NullPointerExceptionInvalid use of a null reference.
NumberFormatExceptionInvalid conversion of a string to a numeric format.
SecurityExceptionAttempt to violate security.
StringIndexOutOfBoundsAttempt to index outside the bounds of a string.
TypeNotPresentExceptionType not found.
UnsupportedOperationExceptionAn unsupported operation was encountered.

The checked exceptions are listed in the following table.

ExceptionMeaning
ClassNotFoundExceptionClass not found.
CloneNotSupportedExceptionAttempt to clone an object that does not implement the Cloneable interface.
IllegalAccessExceptionAccess to a class is denied.
InstantiationExceptionAttempt to create an object of an abstract class or interface.
InterruptedExceptionOne thread has been interrupted by another thread.
NoSuchFieldExceptionA requested field does not exist.
NoSuchMethodExceptionA requested method does not exist.

Java custom exception class

You can create your own exception class by defining a subclass of Exception.

The Exception class does not define any methods of its own. It inherits methods provided by Throwable.

The following program creates a custom exception type.

class MyException extends Exception {
  private int detail;
/* w  w w  .j a v  a2s  . com*/
  MyException(int a) {
    detail = a;
  }

  public String toString() {
    return "MyException[" + detail + "]";
  }
}

public class Main {
  static void compute(int a) throws MyException {
    System.out.println("Called compute(" + a + ")");
    if (a > 10)
      throw new MyException(a);
    System.out.println("Normal exit");
  }

  public static void main(String args[]) {
    try {
      compute(1);
      compute(20);
    } catch (MyException e) {
      System.out.println("Caught " + e);
    }
  }
}

The code above generates the following result.

Java chained exceptions

The chained exception allows you to associate another exception with an exception. This second exception describes the cause of the first exception.

To allow chained exceptions, two constructors and two methods were added to Throwable.

Throwable(Throwable causeExc) 
Throwable(String msg, Throwable causeExc)

Here is an example that illustrates the mechanics of handling chained exceptions:

public class Main {
  static void demoproc() {
    NullPointerException e = new NullPointerException("top layer");
    e.initCause(new ArithmeticException("cause"));
    throw e;//  w  ww  . java  2 s . com
  }

  public static void main(String args[]) {
    try {
      demoproc();
    } catch (NullPointerException e) {
      System.out.println("Caught: " + e);
      System.out.println("Original cause: " + e.getCause());
    }
  }
}

The code above generates the following result.