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

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();
  }

}

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).

A method might throw an Exception type only because a method it called threw that type. For example, a method that does not do any arithmetic might throw an ArithmeticException because a method it called might throw that type.

Inspect the example program. 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.

In this example, methodC attempts I/O and must say throws IOException because it does not handle possible exceptions. But methodB must also say throws IOException because it calls methodC and does not handle exceptions, either. The same applies to methodA and main


QUESTION 7:

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


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