try { Java statements }
It should enclose the exception-throwing statements.
try { int i; pStr = new PrintStream( new BufferedOutputStream( new FileOutputStream("OutFile.txt"))); for (i = 0; i < size; i++) pStr.println("Value at: " + i + " = " + victor.elementAt(i)); }
try { . . . } catch (Throwable e) { . . . } catch ( . . . ) { . . . } . . . catch (SomeThrowableObject variableName) { Java statements }
variableName: is the name by which the handler can refer to the exception caught by the handler.
e.getMessage();
You access the instance variables and methods of exceptions in the same manner that you do with other objects.
try { . . . } catch (ArrayIndexOutOfBoundsException e) { System.err.println("Caught ArrayIndexOutOfBoundsException: " + e.getMessage()); } catch (IOException e) { System.err.println("Caught IOException: " + e.getMessage()); }
If you write a handler for a "leaf" class (a class with no subclasses), you've written a specialized handler: it will only handle exceptions of that specific type.
try { . . . } catch (ArrayIndexOutOfBoundsException e) { System.err.println("Caught ArrayIndexOutOfBoundsException: " + e.getMessage()); } catch (IOException e) { System.err.println("Caught IOException: " + e.getMessage()); }
If you write a handler for a "node" class (a class with subclasses), you've written a general handler: it will handle any exception whose type is the node class or any of its subclasses.
try { . . . } catch (Exception e) { System.err.println("Exception caught: " + e.getMessage()); }
The statements within the finally block are always executed.
To provides a mechanism that allows your method to clean up after itself regardless of what happens within the try block. Use the finally block to close files or release other system resources.
finally { if (pStr != null) { System.out.println("Closing PrintStream"); pStr.close(); } else { System.out.println("PrintStream not open"); } }
![]() | Caution |
---|---|
![]() C++ exception handlers can not have a finally block. |
public void writeList() { PrintStream pStr = null; try { int i; System.out.println("Entering try statement"); pStr = new PrintStream( new BufferedOutputStream( new FileOutputStream("OutFile.txt"))); for (i = 0; i < size; i++) pStr.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 (pStr != null) { System.out.println("Closing PrintStream"); pStr.close(); } else { System.out.println("PrintStream not open"); } } }
Copyright © 1998-2009 Dilvan Moreira