Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the point of the finally block?

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?

like image 807
Keshi Avatar asked Sep 08 '08 20:09

Keshi


People also ask

What is the purpose of the finally block?

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.

Why do we use Finally block in Python?

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.

What is the use of finally?

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.


3 Answers

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.

like image 183
Josh Hinman Avatar answered Oct 14 '22 02:10

Josh Hinman


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.

like image 26
Vinko Vrsalovic Avatar answered Oct 14 '22 02:10

Vinko Vrsalovic


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.

like image 43
SCdF Avatar answered Oct 14 '22 02:10

SCdF