Java Reference
In-Depth Information
your program should handle exceptions of these types. An important subclass of Excep-
tion is RuntimeException , which is used to represent various common types of run-time
errors.
Exception Handling Fundamentals
Java exception handling is managed via five keywords: try , catch , throw , throws , and fi-
nally . They form an interrelated subsystem in which the use of one implies the use of an-
other. Throughout the course of this chapter, each keyword is examined in detail. However,
it is useful at the outset to have a general understanding of the role each plays in exception
handling. Briefly, here is how they work.
Program statements that you want to monitor for exceptions are contained within a try
block. If an exception occurs within the try block, it is thrown . Your code can catch this
exception using catch and handle it in some rational manner. System-generated exceptions
are automatically thrown by the Java run-time system. To manually throw an exception,
use the keyword throw . In some cases, an exception that is thrown out of a method must
be specified as such by a throws clause. Any code that absolutely must be executed upon
exiting from a try block is put in a finally block.
Ask the Expert
Q :
Just to be sure, could you review the conditions that cause an exception to be
generated?
A : Exceptions are generated in three different ways. First, the Java Virtual Machine can
generate an exception in response to some internal error which is beyond your con-
trol. Normally, your program won't handle these types of exceptions. Second, stand-
ard exceptions, such as those corresponding to divide-by-zero or array index out-of-
bounds, are generated by errors in program code. You need to handle these excep-
tions. Third, you can manually generate an exception by using the throw statement.
No matter how an exception is generated, it is handled in the same way.
Using try and catch
Search WWH ::




Custom Search