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

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

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 do we need the “finally” clause in Python?

It makes a difference if you return early: try: run_code1() except TypeError: run_code2() return None # The finally block is run before the method returns finally: other_code() Compare to this: try: run_code1() except TypeError: run_code2() return None other_code() # This doesn’t get run if there’s an exception. Other situations that can cause differences: If an … Read more