Basic exceptions

Bruce Eckel’s Thinking in Java Contents | Prev | Next

A
simple example is a divide. If you’re about to divide by zero, it’s
worth checking to make sure you don’t go ahead and perform the divide.
But what does it mean that the denominator is zero? Maybe you know, in the
context of the problem you’re trying to solve in that particular method,
how to deal with a zero denominator. But if it’s an unexpected value, you
can’t deal with it and so must throw an exception rather than continuing
along that path.

As
a simple example of throwing an exception, consider an object handle called
t.
It’s possible that you might be passed a handle that hasn’t been
initialized, so you might want to check before trying to call a method using
that object handle. You can send information about the error into a larger
context by creating an object representing your information and
“throwing” it out of your current context. This is called
throwing
an exception
.
Here’s what it looks like:

if(t
== null)


throw new NullPointerException();

Exception
arguments

Like
any object in Java, you always create exceptions on the heap using
new
and a constructor gets called. There are two constructors in all the standard
exceptions; the first is the default constructor, and the second takes a string
argument so you can place pertinent information in the exception:

if(t
== null)


throw new NullPointerException("t = null");

This
string can later be extracted using various methods, as will be shown later.

Any
similarity to an ordinary return from a method ends here, because
where
you return is someplace completely different from where you return for a normal
method call. (You end up in an appropriate exception handler that might be
miles away – many levels lower on the call stack – from where the
exception was thrown.)

More by Author

Must Read