Python exceptions (try/except)

Python exceptions #

Example #

try:
    pass
except Exception:
    pass
else:
    pass
finally:
    pass

try/except #

This would generate an error if the file path is invalid (i.e, the file does not exist)

f = open('<path to file>')

To handle the error:

try:
    f = open('<path to file>')
except Exception:
    print('Yo, no file found')

try tries to run some code. If there’s an exception, the flow moves to except.

exception types #

A generic Exception sometimes isn’t helpful with flow or debugging. Specific exceptions can be more helpful.

An error specific to missing files:

try:
    f = open('<path to file>')
    variable = nonexistent_variable # this would be a name error
except FileNotFoundError:
    print('Yo, no file found')

Extending the block above with a catch-all error:

try:
    f = open('<path to file>')
    variable = nonexistent_variable # this would be a name error
except FileNotFoundError:
    print('Yo, no file found')
except Exception:
    print('There was some sort of problem')

In terms of ordering, more generic errors should be placed further down.

Reflecting the true exception #

Rather than using custom exceptions, show the actual exception message:

try:
    f = open('<path to file>')
    variable = nonexistent_variable # this would be a name error
except FileNotFoundError as e:
    print(e)
except Exception:
    print(e)

else #

Runs code when the try clause doesn’t raise an exception.

try:
    f = open('<path to file>') # assume this is valid
except FileNotFoundError as e:
    print(e)
except Exception:
    print(e)
else:
    print(f.read())
    f.close()

Because the try clause in this block is valid, it would proceed to the else and execute it.

This is in else rather than try to be more transparent and specific about possible errors.

finally #

finally clause runs no matter what happens, whether or not there is an error.

try:
    f = open('<path to file>') # assume this is valid
except FileNotFoundError as e:
    print(e)
except Exception:
    print(e)
else:
    print(f.read())
    f.close()
finally:
    print("Finally!")

raise #

raise can be used to manually raise exceptions.

try:
    f = open('<path to file>') # assume this is invalid
    if f.name == '<path to file>'
except FileNotFoundError as e:
    print(e)
except Exception:
    print("Yo, this is not a valid file")
else:
    print(f.read())
    f.close()
finally:
    print("Finally!")

# "Yo, this is not a valid file"
# "Finally!