Java Exception types

In this chapter you will learn:

  1. What are differences between runtime-error and exceptions
  2. What are uncaught exceptions
  3. How to display a description of an exception

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  .co  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;/*from   w w w  .j av  a 2s  . 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;
/*from  www .j a  v  a 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.

Next chapter...

What you will learn in the next chapter:

  1. When to use try and catch statement
  2. Example - How to use Java try catch statement
  3. How to use multiple catch clauses
  4. How to use nested try statements
Home »
  Java Tutorial »
    Java Langauge »
      Java Exception Handling
Java Exception
Java Exception types
Java try catch statement
Java throw statement
Java throws statement
Java finally statement
Java Built-in Exceptions
Java custom exception class
Java chained exceptions