Java Reference
In-Depth Information
53
catch (Exception exception) // does not execute
54
{
55
System.err.println(exception);
56
}
57
finally // executes regardless of what occurs in try...catch
{
System.err.println(
"Finally executed in doesNotThrowException" );
}
58
59
60
61
62
63
System.out.println( "End of method doesNotThrowException" );
64
}
65
} // end class UsingExceptions
Method throwException
Exception handled in method throwException
Finally executed in throwException
Exception handled in main
Method doesNotThrowException
Finally executed in doesNotThrowException
End of method doesNotThrowException
Fig. 11.5 | try catch finally exception-handling mechanism. (Part 2 of 2.)
System.out and System.err are streams —sequences of bytes. While System.out
(known as the standard output stream ) displays a program's output, System.err (known
as the standard error stream ) displays a program's errors. Output from these streams can
be redirected (i.e., sent to somewhere other than the command prompt , such as to a file ).
Using two different streams enables you to easily separate error messages from other
output. For instance, data output from System.err could be sent to a log file, while data
output from System.out can be displayed on the screen. For simplicity, this chapter will
not redirect output from System.err , but will display such messages to the command
prompt . You'll learn more about streams in Chapter 15.
Throwing Exceptions Using the throw Statement
Method main (Fig. 11.5) begins executing, enters its try block and immediately calls
method throwException (line 10). Method throwException throws an Exception . The
statement at line 26 is known as a throw statement —it's executed to indicate that an ex-
ception has occurred. So far, you've caught only exceptions thrown by called methods.
You can throw exceptions yourself by using the throw statement. Just as with exceptions
thrown by the Java API's methods, this indicates to client applications that an error has
occurred. A throw statement specifies an object to be thrown. The operand of a throw can
be of any class derived from class Throwable .
Software Engineering Observation 11.8
When toString is invoked on any Throwable object, its resulting String includes the
descriptive string that was supplied to the constructor, or simply the class name if no
string was supplied.
 
Search WWH ::




Custom Search