What is the point of using an else
clause if there is a return
instruction in the except
clause?
def foo():
try:
# Some code
except:
# Some code
return
else:
# Some code
I'm asking this question because the Django documentation does it at some point, in the vote()
function. Considering that the return
instruction in the except
clause will anyway stop the execution of the function, why did they use an else
clause to isolate the code that should only be executed if no exception was raised? They could have just omitted the else
clause entirely.
If there is no exception in the
try:
suite, then theelse:
suite is executed. In other words, only if there is an actual exception is theexcept:
suite reached and thereturn
statement used.In my view, the
return
statement is what is redundant here; apass
would have sufficed. I'd use anelse:
suite to atry
when there is additional code that should only be executed if no exception is raised, but could raise exceptions itself that should not be caught.You are right that a
return
in theexcept
clause makes using anelse:
for that section of code somewhat redundant. The whole suite could be de-dented and theelse:
line removed: