finally will always run, no matter what the result of try or except is, even if one of them contains break or return def tell_me_about_bad_math(): try: 1/0 except ZeroDivisionError: return 'oops!' finally: print('you did bad math!') print(tell_me_about_bad_math()) Answer from Deleted User on reddit.com
🌐
GeeksforGeeks
geeksforgeeks.org › python › try-except-else-and-finally-in-python
Try, Except, else and Finally in Python - GeeksforGeeks
try: # Some Code.... except: # optional block # Handling of exception (if required) else: # execute if no exception finally: # Some code .....(always executed)
Published   July 15, 2025
Discussions

exception - What is the point of finally in a try catch/except finally statement - Stack Overflow
I have used try-catch/except-finally variants in many languages for years, today someone asked me what is the point of finally and I couldn't answer. Basically why would you put a statement in fina... More on stackoverflow.com
🌐 stackoverflow.com
python - Order of execution in try except finally - Stack Overflow
I never really use finally, so I wanted to test a few things before using it more regularly. I noticed that when running: def f(): try: 1/0 # 1/1 except: print('exce... More on stackoverflow.com
🌐 stackoverflow.com
language agnostic - Why use try … finally without a catch clause? - Software Engineering Stack Exchange
So, even if I handle the exceptions above, I'm still returning NULL or an empty string at some point in the code which should not be reached, often the end of the method/function. I've always managed to restructure the code so that it doesn't have to return NULL, since that absolutely appears to look like less than good practice. ... I am sad that try..finally ... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
try... except... finally!
context managers and the with statement is used to separate the resource management from the exception handling. see also: https://docs.python.org/3/library/contextlib.html More on reddit.com
🌐 r/Python
59
85
October 1, 2023
Top answer
1 of 7
45

You just need two try/finally blocks:

Screen.Cursor:= crHourGlass;
try
  Obj:= TSomeObject.Create;
  try
    // do something
  finally
    Obj.Free;
  end;
finally
  Screen.Cursor:= crDefault;
end;

The guideline to follow is that you should use finally rather than except for protecting resources. As you have observed, if you attempt to do it with except then you are forced to write the finalising code twice.

Once you enter the try/finally block, the code in the finally section is guaranteed to run, no matter what happens between try and finally.

So, in the code above, the outer try/finally ensures that Screen.Cursor is restored in the face of any exceptions. Likewise the inner try/finally ensures that Obj is destroyed in case of any exceptions being raised during its lifetime.


If you want to handle an exception then you need a distinct try/except block. However, in most cases you should not attempt to handle exceptions. Just let it propagate up to the main application exception handler which will show a message to the user.

If you handle the exception to low down the call chain then the calling code will not know that the code it called has failed.

2 of 7
18

As others have explained, you need to protect the cursor change with try finally block. To avoid writing those I use code like this:

unit autoCursor;

interface

uses Controls;

type
  ICursor = interface(IInterface)
  ['{F5B4EB9C-6B74-42A3-B3DC-5068CCCBDA7A}']
  end;

function __SetCursor(const aCursor: TCursor): ICursor;

implementation

uses Forms;

type
  TAutoCursor = class(TInterfacedObject, ICursor)
  private
    FCursor: TCursor;
  public
    constructor Create(const aCursor: TCursor);
    destructor Destroy; override;
  end;

{ TAutoCursor }
constructor TAutoCursor.Create(const aCursor: TCursor);
begin
  inherited Create;
  FCursor := Screen.Cursor;
  Screen.Cursor := aCursor;
end;

destructor TAutoCursor.Destroy;
begin
  Screen.Cursor := FCursor;
  inherited;
end;

function __SetCursor(const aCursor: TCursor): ICursor;
begin
  Result := TAutoCursor.Create(aCursor);
end;

end.

Now you just use it like

uses
   autoCursor;

procedure TForm1.Button1Click(Sender: TObject);
var
  Obj: TSomeObject;
begin
  __SetCursor(crHourGlass);

  Obj:= TSomeObject.Create;
  try
    // do something
  finally
    Obj.Free;
  end;
end;

and Delphi's reference counted interface mechanism takes care of restoring the cursor.

🌐
W3Schools
w3schools.com › python › python_try_except.asp
Python Try Except
try: print("Hello") except: print("Something went wrong") else: print("Nothing went wrong") Try it Yourself » · The finally block, if specified, will be executed regardless if the try block raises an error or not.
🌐
Python documentation
docs.python.org › 3 › tutorial › errors.html
8. Errors and Exceptions — Python 3.14.3 documentation
If an exception occurs during execution of the try clause, the exception may be handled by an except clause. If the exception is not handled by an except clause, the exception is re-raised after the finally clause has been executed.
🌐
Medium
galea.medium.com › pythons-try-except-else-finally-explained-f04d47d57125
Python’s “try except else finally” explained | by Alex Galea | Medium
October 4, 2020 - Understanding else/finally is simple because there are only two cases. The try statement succeeds -> The except statement is skipped -> The else statement runs -> The finally statement runs
Find elsewhere
Top answer
1 of 6
169

The purpose of a finally block is to ensure that code gets run in three circumstances which would not very cleanly be handled using "catch" blocks alone:

  1. If code within the try block exits via fallthrough or return
  2. If code within a catch block either rethrows the caught exception, or--accidentally or intentionally--ends up throwing a new one.
  3. If the code within the try block encounters an exception for which the try has no catch.

One could copy the finally code before every return or throw, and wrap catch blocks within their own try/catch to allow for the possibility of an accidental exception occurring, but it's far easier to forgo all that and simply use a finally block.

BTW, one thing I wish language designers would include would be an exception argument to the finally block, to deal with the case where one needs to clean up after an exception but still wants it to percolate up the call stack (e.g. one could wrap the code for a constructor in such a construct, and Dispose the object under construction if the constructor was going to exit with an exception).

2 of 6
24

To make it even easier to understand:

try { //a }
catch { //b }
//c

In above code, //c won't execute:

  • if you use "return" inside the try block. **
  • if you use "return" inside the catch block. **
  • if you raise any exception inside the catch block.
  • if your try block raises an exception that can't be caught by your catch block.

While in below code:

try { //a }
catch { //b }
finally { //c }

//c will execute no matter what.

🌐
Delphi-PRAXiS
en.delphipraxis.net › delphi questions and answers › general help
Try..except..finally..end; ?? - General Help - Delphi-PRAXiS [en]
October 31, 2025 - Silly question time. Aside from the fact that it is not allowed, why cant/couldnt/shouldnt there be a Try..except..finally..end; construct?
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › csharp › language-reference › statements › exception-handling-statements
Exception-handling statements - throw and try, catch, finally - C# reference | Microsoft Learn
January 20, 2026 - You can use the try statement in any of the following forms: try-catch - to handle exceptions that might occur during execution of the code inside a try block, try-finally - to specify the code that runs when control leaves the try block, and ...
🌐
Quora
quora.com › How-does-the-finally-clause-work-in-Pythons-try-except-blocks
How does the finally clause work in Python's try-except blocks? - Quora
There’s 4 parts - try (and do something useful that may fail), except (something has failed and we need to do something different), else (all is fine, no errors were caught, so time to finish up) and finally (we do this before we exit).
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Statements › try...catch
try...catch - JavaScript | MDN
2 weeks ago - The try...catch statement is comprised of a try block and either a catch block, a finally block, or both. The code in the try block is executed first, and if it throws an exception, the code in the catch block will be executed. The code in the finally block will always be executed before control ...
Top answer
1 of 9
182

It depends on whether you can deal with the exceptions that can be raised at this point or not.

If you can handle the exceptions locally you should, and it is better to handle the error as close to where it is raised as possible.

If you can't handle them locally then just having a try / finally block is perfectly reasonable - assuming there's some code you need to execute regardless of whether the method succeeded or not. For example (from Neil's comment), opening a stream and then passing that stream to an inner method to be loaded is an excellent example of when you'd need try { } finally { }, using the finally clause to ensure that the stream is closed regardless of the success or failure of the read.

However, you will still need an exception handler somewhere in your code - unless you want your application to crash completely of course. It depends on the architecture of your application exactly where that handler is.

2 of 9
40

The finally block is used for code that must always run, whether an error condition (exception) occurred or not.

The code in the finally block is run after the try block completes and, if a caught exception occurred, after the corresponding catch block completes. It is always run, even if an uncaught exception occurred in the try or catch block.

The finally block is typically used for closing files, network connections, etc. that were opened in the try block. The reason is that the file or network connection must be closed, whether the operation using that file or network connection succeeded or whether it failed.

Care should be taken in the finally block to ensure that it does not itself throw an exception. For example, be doubly sure to check all variables for null, etc.

🌐
Oracle
docs.oracle.com › javase › tutorial › essential › exceptions › finally.html
The finally Block (The Java™ Tutorials > Essential Java Classes > Exceptions)
The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a ...
🌐
Real Python
realpython.com › python-exceptions
Python Exceptions: An Introduction – Real Python
December 1, 2024 - That file didn’t exist, but instead of letting the program crash, you caught the FileNotFoundError exception and printed a message to the console. ... Imagine that you always had to implement some sort of action to clean up after executing your code. Python enables you to do so using the finally clause: ... # ... try: linux_interaction() except RuntimeError as error: print(error) else: try: with open("file.log") as file: read_data = file.read() except FileNotFoundError as fnf_error: print(fnf_error) finally: print("Cleaning up, irrespective of any exceptions.")
🌐
Board Infinity
boardinfinity.com › blog › try-except-in-python
Try, Except, Else and Finally in Python | Board Infinity
August 14, 2025 - If the try block successfully does not raise an exception then the code enters into the else block. ... In Python, we use the final keyword, which is executed always even if the exception is not handled and the try-except block is terminated.
🌐
GUVI
guvi.in › hub › python › try-except-finally-in-python
try…except…finally in Python
In Python, the 'try...except...finally' statement is an extended version of the 'try...except' statement that includes a 'finally' block. The 'finally' block is executed regardless of whether an exception occurred or not.
🌐
SmartBear Community
community.smartbear.com › smartbear community › testcomplete › testcomplete questions
Python Error Handling Not Executing Finally Block - TestComplete 14.0 | SmartBear Community
This would then prompt the automation to halt on that exception which is why it doesn't get to the "finally" clause. You can set that to "continue running" as well. See if that corrects your problem. ... * I no longer get a full stack trace in TC 14.0 "Script Test Log" only the error caught in the "except" statement (12.6 did not have this issue)
🌐
W3Schools
w3schools.com › jsref › jsref_try_catch.asp
W3Schools.com
The technical term for this is is: JavaScript throws an exception. JavaScript creates an Error object with two properties: name and message. The try...catch...finally statements combo handles errors without stopping JavaScript.
🌐
Rollbar
rollbar.com › home › when to use try-except vs. try-catch
When to Use Try-Except vs. Try-Catch | Rollbar
July 31, 2023 - The corresponding except block will be executed if an exception arises inside the try block, preventing the application from crashing. If there are no exceptions, the else block will run, and the finally block will always run whether an exception ...