Programming and Problem Solving with Java

(やまだぃちぅ) #1

(^434) | Exceptions and Additional Control Structures
Let’s look at an example of a try-catchstatement to illustrate this process. In the follow-
ing code, note that the first catchhas a parameter of type IOExceptionand the second has a
parameter of ArithmeticException.
try
{
// Some statements
}
catch(IOException ioErr)
{
// Statements to handle IO errors
}
catch(ArithmeticException arithErr)
{
// Statements to handle division by zero
}
The computer begins by executing the statements within the tryblock. If one of them
causes an IOException, then control jumps to the first catchclause. On the other hand, if a
statement causes an ArithmeticException, then control jumps to the second catchclause.
What happens if a statement throws an exception that isn’t among the catchclauses?
In that case, the trystatement fails to catch the error, and its enclosing method throws the
exception to its caller. If the caller doesn’t have a handler for the error, it throws the excep-
tion to its caller, and so on, until the exception is either caught or ends up at the JVM. In the
latter case, the JVM halts the application and displays an error message.
Any object that is passed to a catchclause through its parameter list must have an as-
sociated value-returning method called getMessage. The getMessagemethod returns a string
containing a message. For example, it might contain the name of the file that could not be
opened. Thus you could write the following statement in a catchclause to display a message:
catch(IOException ioErr)
{
out.add(new JLabel("I/O Exception encountered for " +
ioErr.getMessage()));
}
Let’s look at an actual example. Suppose we have prompted the user to enter a file name
into a field. When the user clicks a button, an event handler is called to open that file as a
PrintWriter. We could use the following code in the button event handler to attempt to open
the file. If the file can’t be opened, we display an error message and clear the input field so
that the user can try again.
filename = fileField.getText();
try
{

Free download pdf