Created
March 9, 2016 15:29
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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