Created
December 6, 2018 04:18
-
-
Save jtarang/9c707b3877e53629c9f7ab58471dbb01 to your computer and use it in GitHub Desktop.
Replying to comment on https://realpython.com/python-exceptions/
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 try_except(arg_passed=None): | |
if arg_passed is not None: | |
try: | |
arg_passed['name'] # this will fail cause we passed in a string not a dict | |
except KeyError as e: | |
print('First Except: No key named {} was found'.format(e)) # this should barf that the key doesnt exist in the dictionary | |
except Exception as e: | |
print('2nd Except: {}'.format(e)) # this is going to run when there isnt a keyerror and its something else | |
finally: | |
print('Finally: This prints when nothing else worked from above') # this should be your worst case scenario | |
else: | |
print('Else: No arg was passed!') # you will get this error if nothing was passed in | |
if __name__ == "__main__": | |
try_except() # fail and go to the else | |
try_except(dict(foo="bar")) # fail goes to 1st except | |
try_except("foobar") # fail goes to 2nd except |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment