Syntax aside, what is the difference between
try {
}
catch() {
}
finally {
x = 3;
}
and
try {
}
catch() {
}
x = 3;
edit: in .NET 2.0?
so
try {
throw something maybe
x = 3
}
catch (...) {
x = 3
}
is behaviourally equivalent?
The finally block in java is used to put important codes such as clean up code e.g. closing the file or closing the connection. The finally block executes whether exception rise or not and whether exception handled or not. A finally contains all the crucial statements regardless of the exception occurs or not.
It defines a block of code to run when the try... except...else block is final. The finally block will be executed no matter if the try block raises an error or not. This can be useful to close objects and clean up resources.
You use finally to suggest that something happens after a long period of time, usually later than you wanted or expected it to happen. The word was finally given for us to get on board. The food finally arrived at the end of last week and distribution began.
Well, for one thing, if you RETURN inside your try block, the finally will still run, but code listed below the try-catch-finally block will not.
Depends on the language as there might be some slight semantic differences, but the idea is that it will execute (almost) always, even if the code in the try block threw an exception.
In the second example, if the code in the catch block returns or quits, the x = 3 will not be executed. In the first it will.
In the .NET platform, in some cases the execution of the finally block won't occur: Security Exceptions, Thread suspensions, Computer shut down :), etc.
In Java:
Finally always gets called, regardless of if the exception was correctly caught in catch(), or in fact if you have a catch at all.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With