Wouter wrote:
Daniel T. wrote:
void functionA() {
try {
doThingA();
} catch ( Exception e ) {
doThingB();
} finally {
doThingC();
}
}
void functionB() {
try {
doThingA();
} catch ( Exception e ) {
doThingB();
}
doThingC();
}
Do the above two methods behave differently or do they do the exact
same thing?
TIA
The difference is this:
The statments under the body finally will always be executed, even when
an exception has been catched; thus when an Exception e has been
catched, functionA shall do doThingC, functionB won't.
At least that's what I learned at school.
This is incorrect. If functionB() enters the catch block do to an
exception being thrown, it will still execute doThingC() unless
doThingB() throws an exception. Another differentiating situation is if
doThingA() throws a Throwable that is not an Exception (very unlikely
and poor programming practice).
The simple way to think about this is like so. The finally block is
always executed, even if the result of the function is to throw an
exception. Thus it is a good idea to release resources in finally
blocks, e.g. database connections, etc.
HTH,
Ray
--
XML is the programmer's duct tape.