Java Reference
In-Depth Information
be thrown, so the compiler can enforce the rule that any method calling the method must deal
with the exception. There are two ways that the calling method can do this. The first is the
one we saw earlier, where there is a catch clause that will be the point of return when the
exception is thrown, and where code can be written that deals with the problem reflected in
the exception. But sometimes that isn't possible, so the calling method can also declare that
it throws the exception, in which case the exception is propagated up the stack to the method
that called it (which in turn will be forced by the compiler to either deal with the exception
or declare it as a possible exception that can be thrown). Note that it isn't turtles all the way
down (or, more accurately, exceptions all the way up). Every Java program needs to start with
a method that has the signature:
public static void main(String[] args)
which, you will notice, throws no exceptions. Of course, you can add exceptions to this de-
claration, in which case the exceptions will go all the way up.
While we have explained exceptions as alternate return values that reenter the calling method
at a different spot than from where the method was called, it would be a very bad idea to liter-
ally use them in that way. Sure, you could wrap any kind of object in an Exception , throw the
exception, and then grab the contained object from the Exception object and use it as a return
value. Fortunately, I have never seen anyone actually do this. And while you could do it, it
would be wrong, if for no other reason than that the performance would be terrible. Throwing
an Exception is meant to happen when things are going badly wrong. As such, there is no
reason to make the code that does the throw particularly fast. The construction of a Throw-
able requires getting a lot of state from the machine, so there is a lot of additional overhead
as well.
But mostly you shouldn't do this because it is an abuse of the feature, using it in a way in
which it was never intended to be used. Anyone looking at your code will wonder what you
are doing, and understanding the code will be that much harder. Since the whole purpose of
Java is to aid in writing large-scale systems that can be understood and maintained over time,
using a trick like this defeats the purpose of the language. Knowing that you could do it might
be useful at a bar, but actually doing it should be avoided.
Search WWH ::




Custom Search