Exception Types

The following disgram 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:


java.lang.ArithmeticException: / by zero 
at Main.main(Exc0.java:4)

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;
    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:


java.lang.ArithmeticException: / by zero 
at Main.subroutine(Exc1.java:4) 
at Main.main(Exc1.java:7)
Home 
  Java Book 
    Language Basics  

Exception Handler:
  1. Exception Handling
  2. Exception Types
  3. try and catch
  4. Displaying a Description of an Exception
  5. Multiple catch Clauses
  6. Nested try Statements
  7. Creates and throws an exception
  8. Methods with throws clause
  9. finally
  10. Java's Built-in Exceptions
  11. Creating Your Own Exception Subclasses
  12. Chained Exceptions