Uncaught Exceptions


Before you learn how to handle exceptions in your program, it is useful to see what happens when you don't handle them.

Program
public class Main {
  public static void main(String[] args) {
    int a = 0;
    int b = 12/a;
    System.out.println(b);
  }
}

When the Java run-time system detects an attempt to divide by zero, it creates a new exceptional object and then throws out this exception. This stops the execution of "Main" because once the exception is thrown, it must be caught by an exception handler and dealt with immediately. In this example, we did not provide any exception handlers of our own, so the exception is captured by the default handler provided by the Java Run-Time System. Any exceptions not detected by your program will eventually be processed by the default handler. The default handler display describes a string exception, prints a stack trace from where the exception occurred, and ends the program.

Exception in thread "main" java.lang.ArithmeticException: / by zero
  at Main.main(Main.java:4)

Notice how the class name, "Main"; the method name "main"; the filename "Main.java"; and the line number, 4, are all included in the simple stack trace. Also, notice that the type of exception thrown is a subclass of Exceptions called ArithmeticException, which more specifically describes what type of error happened.