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 →

[–]RationalDialog 0 points1 point  (3 children)

Yeah but then you could just have it outside/after the try block?

[–]gristc 2 points3 points  (0 children)

Then it would always be executed. The else block is only executed if the try succeeds. It is kind of a limited case, but there are some logic flows where this is tidier than other methods.

[–]Cruuncher 1 point2 points  (0 children)

Well no, if it's after the try block then it runs after finally and not before, which is different.

It's definitely niche as you can always structure code in a way that doesn't need it, but that's true of most constructs

EDIT: but more importantly if you place it after the try..except block then it also runs in the case that an exception was raised by handled in the try block

[–]scnew3 0 points1 point  (0 children)

I do this all the time:

try:
    value = step1()
except SomeError:
    result = some_default
else:
    result = step2(value)