Database Reference
In-Depth Information
Primarily, we open a FileInputStream (probably to read the contents of a file). From there, anything
could happen—specifically, an exception could occur.
String doWork() throws Exception {
FileInputStream tempFileIS = new FileInputStream( "C:/Windows/win.ini" );
tempFileIS.open();
//…
if( tempFileIS != null ) tempFileIS.close();
return "success";
}
If an exception were thrown before we close the FileInputStream , then the doWork() method would
throw the exception to whoever called it (see the throws modifier on the line that defines doWork() ). The
line that closes the FileInputStream ( close() method) would never be reached, and in some instances
the file would remain open. This could have dire consequences for applications running on the
computer. In many cases, a file that is currently open in one application cannot be read by another, so a
file that is not closed after an exception might not get backed up, and it might lock up other computer
operations.
Clean Up in a finally Block
With exception handling, there is a third block called finally that can be used, as in Listing 3-5. With
each try block, there must also be a catch block, a finally block or both. We will rarely have a try
without a catch block (see the sidebar called “ try / finally Tack-on Debugging and Synchronization”
later in this chapter). The idea is that whether you complete the try block successfully or generate and
catch an exception before finishing the try , you can do things to clean up in the finally . The finally
block runs, even if your catch block throws an exception. Look at the syntax of the doWork() method in
Listing 3-5.
Listing 3-5. ExceptionDemoB.java
import java.io.FileInputStream;
public class ExceptionDemoB {
public static void main( String[] args ) {
ExceptionDemoB m = new ExceptionDemoB();
System.out.println( m.doWork() );
System.exit(0);
}
String doWork() {
String returnString = "attempt";
FileInputStream tempFileIS = null;
try {
tempFileIS = new FileInputStream( "C:/Windows/win.ini" );
tempFileIS.open();
//…
returnString = "success";
} catch( Exception x ) {
System.out.println( x.toString() );
 
Search WWH ::




Custom Search