Java Reference
In-Depth Information
Figure 11.2
Output of the CatchDemo program when the file is not found.
In Figure 11.2, the file not_there.txt does not exist, and a FileNotFound-
Exception occurs at the following statement:
file = new FileInputStream(fileName);
The FileNotFoundException catch block catches the exception in the vari-
able f, uses f to print out the stack trace, and returns a -1. That ends the method
call and flow of control returns back to main().
Now let's run the program again, this time where the file exists and the
read() is also successful; hence no exceptions occur. Figure 11.3 shows an
example of what the output will look like.
Multiple catch Blocks
A try block can be followed by multiple catch blocks. The syntax for multiple
catch blocks looks like the following:
try
{
//Protected code
}catch( ExceptionType1 e1)
{
//Catch block
}catch( ExceptionType2 e2)
{
//Catch block
}catch( ExceptionType3 e3)
{
//Catch block
}
Search WWH ::




Custom Search