Java Reference
In-Depth Information
Chapter 7
Exceptions
WHAT YOU WILL LEARN IN THIS CHAPTER
• What an exception is
• How you handle exceptions in your programs
• The standard exceptions in Java
• How to guarantee that a particular block of code in a method will always be executed
• How to define and use your own types of exceptions
• How to throw exceptions in your programs
Java uses exceptions as a way of signaling problems when you execute a program. Exceptions act as a control
mechanism through which a program may be able to recover from an exceptional event. They provide im-
portant debug information (through stack traces) that help you figure what went wrong. Problems signaled
by exceptions can be, but aren't always, serious (as I describe later in this chapter). The standard classes use
them extensively. Because they arise in your Java programs when things go wrong — and if something can
go wrong in your code, sooner or later it will — they are a very basic consideration when you are designing
and writing your programs.
The reason I've been sidestepping the question of exceptions for the past six chapters is that you first
needed to understand classes and inheritance before you could understand what an exception is and appreciate
what happens when an exception occurs. Now that you have a good grasp of these topics I can delve into how
to use and deal with exceptions in a program.
THE IDEA BEHIND EXCEPTIONS
An exception usually signals an error and is so called because errors in your Java programs are bound to be
the exception rather than the rule — by definition! An exception doesn't always indicate an error though —
it can also signal some particularly unusual event in your program that deserves special attention.
If you try to deal with the myriad and often highly unusual and often unexpected error conditions that
might arise in your application code, your program structure soon becomes very complicated and difficult to
understand. One major benefit of having an error signaled by an exception is that it separates the code that
deals with errors from the code that is executed when things are moving along smoothly. Another positive as-
pect of exceptions is that they provide a way of enforcing a response to particular errors. With many kinds of
exceptions, you must include code in your program to deal with them; otherwise, your code does not compile.
These exceptions are referred to as checkedexceptions . Uncheckedexceptions are exceptions where you have
the option of dealing with them or not.
Search WWH ::




Custom Search