Runtime Exceptions The Controversy

Because the Java programming language does not require methods to catch or to specify runtime exceptions, programmers can be tempted to write code that throws only runtime exceptions or to make all their exception subclasses inherit from RuntimeException. Both of these shortcuts allow programmers to write code without bothering with all the nagging errors from the compiler and without bothering to specify or to catch any exceptions. Although this may seem convenient to the programmer, it sidesteps the intent of the catch or specify requirement and can cause problems for programmers using your classes.

Why did the designers decide to force a method to specify all uncaught checked exceptions that can be thrown within its scope? Any exception that can be thrown by a method is part of the method's public programming interface. Callers of a method must know about the exceptions that a method can throw, in order to intelligently and consciously decide what to do about them. These exceptions are as much a part of that method's programming interface as its parameters and return value.

Your next question might be, Well, then, if it's so good to document a method's API, including the exceptions it can throw, why not specify runtime exceptions, too? Runtime exceptions represent problems that are detected by the runtime system. Such problems include arithmetic exceptions (such as dividing by zero), pointer exceptions (such as trying to access an object through a null reference), and indexing exceptions (such as attempting to access an array element through an index that is too large or too small). Runtime exceptions can occur anywhere in a program and in a typical program can be very numerous. The cost of checking for runtime exceptions can exceed the benefit of catching or specifying them. Thus, the compiler does not require that you catch or specify runtime exceptions, although you can.

What do you gain if you throw a RuntimeException or create a subclass of RuntimeException just because you don't want to deal with specifying it? Simply, you get the ability to throw an exception without specifying that you do so. In other words, it is a way to avoid documenting the exceptions that a method can throw. When is this good? Well, when is it ever good to avoid documenting a method's behavior? The answer is, hardly ever. So, generally speaking, do not throw a RuntimeException or create a subclass of RuntimeException simply because you don't want to be bothered with specifying the exceptions that your methods can throw.

Категории