Basic exceptions

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

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.

a simple example of throwing an exception, consider an object handle called
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
an exception
Here’s what it looks like:

== null)

throw new NullPointerException();


any object in Java, you always create exceptions on the heap using
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:

== null)

throw new NullPointerException("t = null");

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

similarity to an ordinary return from a method ends here, because
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