Java Reference
In-Depth Information
public SunSpotException(String msg) {
super(msg);
}
}
Combining throws , try , and throw
What if you want to combine all the approaches shown so far? You want to handle
incoming exceptions yourself in your method, but also you want the option to pass the
exception on to your method's caller. Simply using try and catch doesn't pass on the
exception, and adding a throws clause doesn't give you a chance to deal with the excep-
tion.
If you want to both manage the exception and pass it on to the caller, use all three mech-
anisms: the throws clause, the try statement, and a throw statement to explicitly rethrow
the exception.
Here's a method that uses this technique:
public void readMessage() throws IOException {
MessageReader mr = new MessageReader();
try {
mr.loadHeader();
} catch (IOException e) {
// do something to handle the
// IO exception and then rethrow
// the exception ...
throw e;
}
}
This works because exception handlers can be nested. You handle the exception by doing
something responsible with it but decide that it is important enough to give the method's
caller a chance to handle it as well.
Exceptions can float all the way up the chain of method callers this way (usually not
being handled by most of them) until, at last, the system itself handles any uncaught
exceptions by aborting your program and printing an error message.
If it's possible for you to catch an exception and do something intelligent with it, you
should.
7
Search WWH ::




Custom Search