Java Reference
In-Depth Information
} catch (NumberFormatException|NullPointerException ex) {
// logging
}
For more information regarding catching multiple exceptions, see Recipe 9-4.
Note Be careful when throwing an exception. If the thrown exception is not caught,
it will propagate up the call stack; and if there isn't any catch clause capable of hand-
ling the exception, it will cause the running thread to terminate (also known as unravel-
ing ). If your program has only one main thread, an uncaught exception will terminate
your program.
9-2. Guaranteeing A Block Of Code is
Executed
Problem
You want to write code that executes when control leaves a code segment, even if con-
trol leaves due to an error being thrown or the segment ending abnormally. For ex-
ample, you have acquired a lock and want to be sure that you are releasing it correctly.
You want to release the lock in the event of an error and also in the event of no error.
Solution
Use a try / catch / finally block to properly release locks and other resources that
you acquire in a code segment. Place the code that you want to have executed regard-
less of exceptions into the finally clause. In the example, the finally keyword
specifies a code block that will always execute, regardless of whether an exception was
thrown in the try block. Within the finally block, the lock is released by calling
lock.unlock():
private void callFunctionThatHoldsLock() {
myLock.lock();
Search WWH ::




Custom Search