Homesweet Learning helps students learn!
Exception Handling

The Java programming language uses exceptions to handle errors and other exceptional events. The term exception is shorthand for the phrase "exceptional event."

When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception.

After a method throws an exception, the runtime system attempts to find something to handle it. The set of possible "somethings" to handle the exception is the ordered list of methods that had been called to get to the method where the error occurred. The list of methods is known as the call stack.

The runtime system searches the call stack for a method that contains a block of code that can handle the exception. This block of code is called an exception handler. The search begins with the method in which the error occurred and proceeds through the call stack in the reverse order in which the methods were called. When an appropriate handler is found, the runtime system passes the exception to the handler. An exception handler is considered appropriate if the type of the exception object thrown matches the type that can be handled by the handler.

The exception handler chosen is said to catch the exception. If the runtime system exhaustively searches all the methods on the call stack without finding an appropriate exception handler, as shown in the next figure, the runtime system (and, consequently, the program) terminates.

The following example program shows you how an exception object "NumberFormatExcception" is created, handed off to the runtime system, and caught by the "catch" and "finally" blocks in the same method. Run this program in your own Eclipse environment to know the logic of the try-catch-finally block

package com.example.learn;
import java.io.*;
public class ExceptionTest {
  public static void main(String argv[]){
    (new ExceptionTest()).amethod(0);
  }

  public boolean amethod(int i){
    try{
      //DataInputStream din = new DataInputStream(System.in);
      System.out.println("Pausing");
      //din.readChar();
      System.out.println("Continuing");
      if (i==0)
        throw new NumberFormatException();
      else if (i==2)
        throw new IOException();
      //return true;
    }catch(IOException ioe) {
      System.out.println("Continuing");
      return true;
    } finally{
      System.out.println("Doing finally");
    }
    System.out.println("return from amethod");
    return false;
  }
} 

If you want to throw an exception outside of your method, you need to specify it in defining the method. Here is how to do it:

public String test() throws IOException {
......
}

However, you don't have to specify RuntimeException & its subclasses. RuntimeException is the superclass of those exceptions that can be thrown during the normal operation of the Java Virtual Machine. RuntimeException and its subclasses are unchecked exceptions. Unchecked exceptions do not need to be declared in a method or constructor's throws clause if they can be thrown by the execution of the method or constructor and propagate outside the method or constructor boundary. For more about RuntimeException and its subclasses, refer to http://docs.oracle.com/javase/7/docs/api/java/lang/RuntimeException.html.

The following code will not compile. Why?

try{
  DataInputStream dis = new DataInputStream(System.in);
  dis.read();
}catch (Exception ioe) {
}catch (IOException e) {
}finally{
}

This code will give an error message at compile time that the more specific IOException will never be reached.

Lab: Design a program that takes user input and convert them into integers. If the user input cannot be converted into integers, throw an exception and in the same method, catch the exception and print a user-friendly message to the user to tell him to enter again.