How to correctly write Try..Finally..Except statements?

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 … Read more

Why does a return in `finally` override `return` value in `try` block?

Finally always executes. That’s what it’s for, which means its return value gets used in your case. You’ll want to change your code so it’s more like this: function example() { var returnState = false; // initialization value is really up to the design try { returnState = true; } catch { returnState = false; … Read more

Why does try..finally block not register the original exception as suppressed?

Because try-with-resources is syntactic sugar and the Java compiler doesn’t expand regular try-finally blocks in the same way. Take a look at the following code: try(FileInputStream fstream = new FileInputStream(“test”)) { fstream.read(); } When compiled and then decompiled (using IntelliJ IDEA) it looks like this: FileInputStream fstream = new FileInputStream(“test”); Throwable var2 = null; try … Read more

Python: Using continue in a try-finally statement in a loop

From the python docs: When a return, break or continue statement is executed in the try suite of a try…finally statement, the finally clause is also executed β€˜on the way out.’ A continue statement is illegal in the finally clause. (The reason is a problem with the current implementation β€” this restriction may be lifted … Read more

What happens if both catch and finally blocks throw exception?

When the finally block throws an exception, it will effectively hide the exception thrown from the catch block and will be the one ultimately thrown. It is therefore important to either log exceptions when caught, or make sure that the finally block does not itself throw an exception, otherwise you can get exceptions being thrown … Read more

How to determine if an exception was raised once you’re in the finally block?

Using a contextmanager You could use a custom contextmanager, for example: class DidWeRaise: __slots__ = (‘exception_happened’, ) # instances will take less memory def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): # If no exception happened the `exc_type` is None self.exception_happened = exc_type is not None And then use that inside the try: try: … Read more

Overhead of try/finally in C#?

Why not look at what you actually get? Here is a simple chunk of code in C#: static void Main(string[] args) { int i = 0; try { i = 1; Console.WriteLine(i); return; } finally { Console.WriteLine(“finally.”); } } And here is the resulting IL in the debug build: .method private hidebysig static void Main(string[] … Read more