-8

Suppose I want to run some function in Python, ensuring that whether it fails or not some cleanup code is always run. Something like this:

try: some_function()
finally: cleanup()

Ok, simple enough. But hold up! If any exceptions occur in the try block, they'll be suppressed. So really this construct did more than I wanted. All I really wanted to do was make sure some cleanup code runs after the function whether it finishes successfully or not. I still want any exceptions which occur in my function to happen normally. Perhaps that would look something like this:

do: some_function()
finally: cleanup()

Of course, that isn't real Python code. The actual way which I've found to do this is like follows:

try: some_function()
except Exception as error: raise error
finally: cleanup()

Eww, gross. I'm adding an extra line to re-throw an exception which I wanted to just happen normally in the first place. And additionally the stack trace now has an extra line in it showing the except Exception as error: raise error bit. This seems less than ideal to me, but it also seems to be the only way to accomplish what I'm trying to do.

So is this really the way I'm supposed to go about this?

If yes, then I have a further question: Why doesn't Python have a dedicated construct for simply ensuring some block of code runs whether some other block succeeds or not?

As far as my small mind is concerned, this whole idea has little to do with exception handling, since I don't actually want to keep exceptions from occurring where they normally would in the stack trace. Therefore, forcing people to use a try-except-finally construct seems just weird to me.

Aaron Beaudoin
  • 1,107
  • 1
  • 10
  • 23
  • 4
    "If any exceptions occur in the try block, they'll be suppressed" - uh, no? `finally` doesn't do that. – user2357112 Apr 25 '19 at 06:19
  • 4
    `finally` is already exactly the mechanism you're looking for. You've just got some weird, wrong idea about what it does, maybe because you `return`ed in a `finally` once and suppressed exceptions that way, or because you thought that `try` rather than `except` is the part that catches exceptions. – user2357112 Apr 25 '19 at 06:21
  • 1
    [Here, watch a `finally` not suppress anything.](https://ideone.com/CtTqdL) – user2357112 Apr 25 '19 at 06:24
  • Sounds like some first world problem :) – Nuhman Apr 25 '19 at 06:25

2 Answers2

1

Python does!

try:
    1/0
finally:
    print("Hello, world!")
print("This will not print.")
wizzwizz4
  • 6,140
  • 2
  • 26
  • 62
0

Alright so as @user2357112 pointed out it looks like I somehow had the wild misconception that the try part of a try-except-finally construct is what catches exceptions. If anyone else gets confused similarly... it's the except bit that does the catching. Pretty obvious after some thinking, but hey everyone has brain farts sometimes.

Aaron Beaudoin
  • 1,107
  • 1
  • 10
  • 23