|
|
Handling Errors with Exceptions |
The previous sections describe how to construct thetry,catch, andfinallycode blocks for thewriteListexample. Now, let's walk through the code and investigate what happens during three scenarios.When all of the components are put together, the
writeListmethod looks like this:Thispublic void writeList() { PrintWriter out = null; try { System.out.println("Entering try statement"); out = new PrintWriter( new FileWriter("OutFile.txt")); for (int i = 0; i < size; i++) out.println("Value at: " + i + " = " + victor.elementAt(i)); } catch (ArrayIndexOutOfBoundsException e) { System.err.println("Caught ArrayIndexOutOfBoundsException: " + e.getMessage()); } catch (IOException e) { System.err.println("Caught IOException: " + e.getMessage()); } finally { if (out != null) { System.out.println("Closing PrintWriter"); out.close(); } else { System.out.println("PrintWriter not open"); } } }tryblock in this method has three different exit possibilities:This section investigates in detail what happens in the
- The
new FileWriterstatement fails and throws anIOException.- The
victor.elementAt(i)statement fails and throws anArrayIndexOutOfBoundsException.- Everything succeeds and the
trystatement exits normally.writeListmethod during each of those exit possibilities.Scenario 1: An
IOExceptionOccursThenew FileWriter("OutFile.txt")statement can fail for any number of reasons: the user doesn't have write permission on the file or directory, the file system is full, or the directory for the file doesn't exist. If any of these situations is true, then the constructor forFileWriterthrows anIOException.When the
IOExceptionis thrown, the runtime system immediately stops execution of thetryblock. Then the runtime system attempts to locate an exception handler appropriate for handling anIOException.The runtime system begins its search at the top of the method call stack. When the exception occurred, the
FileWriterconstructor was at the top of the call stack. However, theFileWriterconstructor doesn't have an appropriate exception handler so the runtime system checks the next method in the method call stack--thewriteListmethod. ThewriteListmethod has two exception handlers: one forArrayIndexOutofBoundsExceptionand one forIOException.The runtime system checks
writeList's handlers in the order that they appear following thetrystatement. The argument to the first exception handler isArrayIndexOutofBoundsException, but the exception that was thrown is anIOException. AnIOExceptioncannot legally be assigned to anArrayIndexOutofBoundsException, so the runtime system continues its search for an appropriate exception handler.The argument to
writeList's second exception handler is anIOException. The exception thrown by theFileWriterconstructor is also anIOExceptionand can be legally assigned to the handler'sIOExceptionargument. Thus, this handler is deemed appropriate and the runtime system executes this handler, which prints this statement:Caught IOException: OutFile.txtAfter the exception handler has run, the runtime system passes control to the
finallyblock. In this particular scenario, thePrintWriternever was opened, and thusoutis null and won't get closed. After thefinallyblock has completed executing, the program continues with the first statement after thefinallyblock.The complete output that you see from the
ListOfNumbersprogram when anIOExceptionis thrown is this:Entering try statement Caught IOException: OutFile.txt PrintWriter not openScenario 2: An
ArrayIndexOutofBoundsExceptionOccursThis scenario is the same as the first except that a different error occurs during thetryblock. In this scenario, the argument passed to theVector'selementAtmethod is out of bounds. That is, the argument is either less than 0 or is larger than the size of the array. (The way the code is written, this is actually impossible, but let's suppose a bug is introduced into the code when someone modifies it.)As in to scenario 1, when the exception occurs the runtime system stops execution of the
tryblock and attempts to locate an exception handler suitable for anArrayIndexOutofBoundsException. The runtime system searches for an appropriate exception handler as it did before. It comes upon thecatchstatement in thewriteListmethod that handles exceptions of the typeArrayIndexOutofBoundsException. Since the type of the thrown exception matches the type of the exception handler, the runtime system executes this exception handler.After the exception handler has run, the runtime system passes control to the
finallyblock. In this particular scenario, thePrintWriterdid get opened, thus thefinallystatement closes it. After thefinallyblock has completed executing, the program continues with the first statement after thefinallyblock.The complete output that you see from the
ListOfNumbersprogram when anArrayIndexOutofBoundsExceptionis thrown is something like this:Entering try statement Caught ArrayIndexOutOfBoundsException: 10 >= 10 Closing PrintWriterScenario 3: The
tryblock exits normallyIn this scenario, all the statements within the scope of thetryblock execute successfully and throw no exceptions. Execution falls off the end of thetryblock, and then the runtime system passes control to thefinallyblock. Since everything was successful, thePrintWriteris open when control reaches thefinallyblock, which closes thePrintWriter. Again, after thefinallyblock has completed executing, the program continues with the first statement after thefinallyblock.Thus, the output that you see from the
ListOfNumbersprogram when no exceptions are thrown is:Entering try statement Closing PrintWriter
|
|
Handling Errors with Exceptions |