Java Reference
In-Depth Information
In a method that is ready to handle a particular exception type, place the statements
that can cause the exception inside a
try
block, and the handler inside a
catch
clause.
You install an exception handler with the
try/catch
statement. Each
try
block
contains one or more statements that may cause an exception.
Each catch
clause
contains the handler for an exception type. Here is an example:
try
{
String filename = . . .;
FileReader reader = new FileReader(filename);
Scanner in = new Scanner(reader);
String input = in.next();
int value = Integer.parseInt(input);
. . .
}
catch (IOException exception)
{
exception.printStackTrace();
}
catch (NumberFormatException exception)
{
System.out.println("Input was not a number");
}
508
509
Three exceptions may be thrown in this
try
block: The
FileReader
constructor
can throw a
FileNotFoundException
,
Scanner.next
can throw a
NoSuchElementException
, and
Integer.parseInt
can throw a
NumberFormatException
.
S
YNTAX
11.3 General
try
Block
try
{
statement
statement
. . .
}
catch (ExceptionClass exceptionObject)
{