|
|
|
|
When you're writing a program, you will often be confronted with the task of throwing an exception to indicate that some problem has occurred. Here are some questions you should ask when you encounter this situation: What Should I Throw?Well, you know that whatever you throw, it has to be a subclass of Throwable, or the compiler won't let you do it. But, aside from that, what choices do you have? It's discouraged to use Errors, unless you're doing something very special, probably with the Java Virtual Machine itself. Here's a list of possibilities:
You should familiarize yourself with the set of exception classes already available to you, because it's possible that one of them would be an appropriate choice for your situation. Look at them first. Failing that, you have to write your own exception class. Writing Your Own Exception ClassOnce you've made the decision to write your own exception class, you will have to decide what to use as a superclass. First, see whether there is another exception class that it would be appropriate to extend. If there is, then use that as the superclass. Another issue is whether you wish to have this exception be a standalong exception, or whether it should be one of a family (hierarchy) of related exceptions. Often,the family is very useful, and it can save lots of cases where methods have long lists of throws exceptions, and lots of lengthy catch blocks. If you decide to make a family of exceptions, or add to an existing family, then you will have to come up with the appropriate exception class to use as a superclass. If you decide not to include the exception into an exception family, then you can use the Exception class as the superclass:
(filling in the details represented by the above ... ). Note: It's standard practice to append the string "Exception" to the names of all classes that are subclasses (directly or indirectly) of class Exception. Similarly, if you are writing a subclass of the Error class, it should end its name with the string "Error". How Should I Throw It?This is easy: Use the throw statement: throw <exception> Usually, the exception's constructor is used, something like this: throw new EmptyStackException(); or, if you wish to supply more information with the exception:
However, if you have an instance of the approporiate
exception class already in existance, you can throw it
directly.
|
| The page was last updated February 19, 2008 |