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 thereturnstatement used.In my view, the
returnstatement is what is redundant here; apasswould have sufficed. I'd use anelse:suite to atrywhen 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
returnin theexceptclause makes using anelse:for that section of code somewhat redundant. The whole suite could be de-dented and theelse:line removed: