go to previous page   go to home page   go to next page        

Answer:

  1. Handle it in a catch{} block, or
  2. throw it to the method's caller.

Passing the Buck

If a method throws a checked exception up to its caller, the caller must do one of the same two things. And if the caller throws the exception to its caller, then its caller must do one of the same two things, and so on. Ultimately the exception will be handled, possibly by the runtime system (which terminates the program and prints the stack trace). Here is an outline of some code:

public class BuckPassing
{

  public static void methodC() throws IOException
  {
     // Some I/O statements
  }

  public static void methodB() throws IOException
  {
     methodC();
  }

  public static void methodA() throws IOException
  {
     methodB();
  }

  public static void main ( String[] a ) throws IOException
  {
     methodA();
  }

}

Every method in this example throws IOExceptions back to its caller. Say that an IOException happens in methodC(). It throws the exception to methodB(), which throws it to methodA(), which throws it to main(). The exception finally reaches the run time system, which terminates the program and prints a stack trace.

QUESTION 7:

If an IOException occurs in methodC(), how does the stack trace look (roughly)?