What\'s the difference between
try {
fooBar();
} finally {
barFoo();
}
and
try {
fooBar();
} catch(Throwable thro
These are not variations, they're fundamentally different things. finally
is executed always, catch
only when an exception occurs.
Finally block is always executed. Catch block is executed only when an exception that matches the blocks parameter is catched.
Even in the first form you could log it in the calling method. So there is no big advantage unless you want to do some special handling right there.
try {
statements;
} catch (exceptionType1 e1) { // one or multiple
statements;
} catch (exceptionType2 e2) {
statements;
}
...
} finally { // one or none
statements;
}
No Matter what The Finally block is always executed, So in General, Finally block is used, when you have sessions, Database connections or Files or sockets are open, then the code for closing those connections will be placed. This is just to make sure in an application no memory leaks or Any other issues should not occur.
Finally and catch blocks are quite different:
So
try {
//some code
}
catch (ExceptionA) {
// Only gets executed if ExceptionA
// was thrown in try block
}
catch (ExceptionB) {
// Only executed if ExceptionB was thrown in try
// and not handled by first catch block
}
differs from
try {
//some code
}
finally {
// Gets executed whether or not
// an exception was thrown in try block
}
significantly.
If you define a try block you have to define
So the following code would be valid too:
try {
//some code
}
catch (ExceptionA) {
// Only gets executed if
// ExceptionA was thrown in try block
}
catch (ExceptionB) {
// Only executed if ExceptionB was thrown in
// try and not handled by first catch block
}
//even more catch blocks
finally {
// Gets executed whether or not an
// exception was thrown in try block
}