
2023-06-30 19:54 UTC+02:00, MRAB <python@mrabarnett.plus.com>:
On 2023-06-30 14:55, Daniel Walker wrote:
As most of you probably know, you can use else with try blocks:
try: do_stuff() except SomeExceptionClass: handle_error() else: no_error_occurred()
Here, no_error_occurred will only be called if do_stuff() didn't raise an exception.
However, the following is invalid syntax:
try: do_stuff() else: no_error_occurred()
Now you might say that this isn't needed as you can achieve the same result with
do_stuff() no_error_occurred()
However, what if I want to use finally as well:
try: do_stuff() else: no_error_occurred() finally: cleanup()
and I need no_error_occurred to be called before cleanup? For my actual use case, I've done
try: do_stuff() except Exception: raise else: no_error_occurred() finally: cleanup()
This seems very non-Pythonic. Is there a reason why else without except has to be invalid syntax?
What would be the difference between
try: do_stuff() else: no_error_occurred() finally: cleanup()
and
try: do_stuff() no_error_occurred() finally: cleanup()
?
One could argue that it's conceptually not the same although the actual execution is the same. In the first case you intend to only catch the exceptions generated by do_stuff(). In the second case, you intend to catch those generated by do_stuff() and those generated by no_error_occurred(). If later on an "except" is added, the developper doing the modification should be reminded to move the call to no_error_occurred() into an "else". With real-world non-trivial code, it might not be so simple to see. I'm not an expert, but I actually see no downside to having an "else" without an "except". Best regards, Celelibi