Skip to content

Instantly share code, notes, and snippets.

@thigm85
Created March 9, 2016 15:29
Show Gist options
  • Save thigm85/c6a4848d56bb54e4d84a to your computer and use it in GitHub Desktop.
Save thigm85/c6a4848d56bb54e4d84a to your computer and use it in GitHub Desktop.
Example of using the optional finally clause in python exceptions. Reference: https://docs.python.org/2/tutorial/errors.html#defining-clean-up-actions
def divide(x, y):
try:
result = x / y
except ZeroDivisionError:
print "division by zero!"
else:
print "result is", result
finally:
print "executing finally clause"
divide(2, 1) # finally clause executed when no expection raise
# Output:
# result is 2
# executing finally clause
divide(2, 0) # finally clause executed when exception is handled
# Output:
# division by zero!
# executing finally clause
divide("2", "1") # finally clause executed and unhandled exception re-raised
# Output:
# executing finally clause
# Traceback (most recent call last):
# File "<stdin>", line 1, in ?
# File "<stdin>", line 3, in divide
# TypeError: unsupported operand type(s) for /: 'str' and 'str'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment