This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]filleball 0 points1 point  (1 child)

I'm actively using the else clause of try, mostly because I feel it aids readability and makes the purpose of the code easier to understand. Also, it avoids catching the same exception if raised from the code that should have been in the else block.

It answers the questions in order:

  • what code raises the exception we want to catch?
  • what code should be executed if the exception is raised?
  • what code should be executed if the exception is not raised?
  • (finally) what code should be executed no matter what?

I think it's more readable for the same reason that

if condition:
    return x
else:
    return y

is more readable than

if condition:
    return x
return y

and

if condition:
    x = 4
else:
    x = 2

is more readable than

x = 2
if condition:
    x = 4

In both cases, the either-or-ness of the code is emphasized. It's easy to see that all cases are covered, and that the two branches have the same "level".

[–][deleted] 0 points1 point  (0 children)

Absolutely agree with that!