[Django]-Use case of try-except-else statement

4๐Ÿ‘

โœ…

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
๐Ÿ‘คMartijn Pieters

4๐Ÿ‘

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

๐Ÿ‘คM4rtini

Leave a comment