Class 2 |
Intermediate Java 30-IT-397 |
|
Informing Others
-
When you return a value from a method, you state that in the method signature.
-
public String getName() { for example.
-
The same goes for exceptions. You have to tell the calling method
that you might throw an exception, and the calling method either has to
handle that exception, or throw that same exception itself.
-
In other words, if you plan on throwing an exception, the calling method
must have an exception handler, or throw it to a method that does
have an exception handler.
-
Interestingly, the exception handler counts if it is a superclass of the
exception you are throwing. In other words, an IOException can be
handled by a handler for IOException, RuntimeException, or Exception.
As long as a hander in the calling method is of one of those types, you're
fine.
-
So, how do you do it?
-
Add throws Exception after the method signature. Exception
can be the name of any subclass that extends Exception, or Exception
itself.
-
Examples:
-
public String getName() throws IOException {
-
public String getName() throws Exception {
-
You can even declare it to throw multiple Exceptions if you like.
-
public String getName() throws IOException, ArithmeticException {
-
Or, you can throw multiple exceptions, and only list one Exception class
name, as long as that class is a superclass of all of the exceptions thrown.
-
In other words, the above line can be condensed to: public String getName()
throws Exception {
-
For certain errors, you must declare the exception in the signature.
-
If you call a method that throws a checked exception.
-
If you throw an exception yourself with the throw keyword.
We'll cover this later.
-
A checked exception is an exception that you know might be thrown.
-
For other errors, you do not have to declare the exception.
-
Making a programming error that causes an unchecked exception.
-
An internal error occurs.
-
Unchecked exceptions are exceptions that are so common that, if
you did have to delcare them, you'd have to declare them in almost ever
method! They are either beyond your control, or result from conditions
that you should not have allowed in the first place.
Throwing an Exception

Created by: Brandan Jones
December 17, 2001