Question

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.

Was it helpful?

Solution

If there is no exception in the try: suite, then the else: suite is executed. In other words, only if there is an actual exception is the except: suite reached and the return statement used.

In my view, the return statement is what is redundant here; a pass would have sufficed. I'd use an else: suite to a try 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 the except clause makes using an else: for that section of code somewhat redundant. The whole suite could be de-dented and the else: line removed:

def foo():
    try:
        # Some code
    except:
        # Some code
        return

    # Some code

OTHER TIPS

From the docs: The use of the else clause is better than adding additional code to the try clause because it avoids accidentally catching an exception that wasn’t raised by the code being protected by the try ... except statement. http://docs.python.org/2/tutorial/errors.html#handling-exceptions

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top