Java Reference
In-Depth Information
9.1
Exception Handling Basics
Well the program works for most cases. I didn't know it had to work for
that
case.
COMPUTER SCIENCE STUDENT,
appealing a grade
Exception handling is meant to be used sparingly and in some situations that are more
involved than what is reasonable to include in an introductory example. So, in some cases,
we will teach you the exception handling details of Java by means of simple examples
that would not normally use exception handling. This makes a lot of sense for learning
about the exception handling details of Java, but do not forget that these examples are toy
examples and, in practice, you would not use exception handling for anything this simple.
try-catch
Mechanism
The basic way of handling exceptions in Java consists of the
try-throw-catch
trio. At
this point, we will start with only
try
and
catch
. The general setup consists of a
try
block followed by one or more
catch
blocks. First let's describe what a try block is. A
try
block
has the following syntax:
try
block
try
{
Some_Code_That_May_Throw_An_Exception
}
This
try
block contains the code for the basic algorithm that tells what to do when
everything goes smoothly. It is called a
try
block because it “tries” to execute the case
where all goes well.
Now, an exception can be “thrown” as a way of indicating that something unusual
happened. For example, if our code tries to divide by zero, then an
ArithmeticException
object is thrown. In most of this chapter, our own code will throw the exception, but
initially we will have existing Java classes do the throwing.
As the name suggests, when something is “thrown,” something goes from one place
to another place. In Java, what goes from one place to another is the flow of control
as well as the exception object that is thrown. When an exception is thrown, the code
in the surrounding
try
block stops executing and (normally) another portion of code,
known as a
catch
block
, begins execution. The
catch
block has a parameter, and the
exception object thrown is plugged in for this
catch
block parameter. This executing
of the
catch
block is called
catching the exception
or
handling the exception
. When
an exception is thrown, it should ultimately be handled by (caught by) some
catch
block. The appropriate
catch
block immediately follows the
try
block; for example,
catch
block
handling an
exception
catch
(Exception e)
{
String message = e.getMessage();
System.out.println(message);
System.exit(0);
}