Skip to content

Instantly share code, notes, and snippets.

@raheemazeezabiodun
Created September 19, 2019 21:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raheemazeezabiodun/9d7b17a2dc390b8a0751bbcefc7a9e22 to your computer and use it in GitHub Desktop.
Save raheemazeezabiodun/9d7b17a2dc390b8a0751bbcefc7a9e22 to your computer and use it in GitHub Desktop.
An example of how to use try except else in Python
"""
The try block tries to execute an expression
If an error occurs, it calls the except block alone
If no error occur, it calls the else block
The idea behind this is, if the school exists, print it out
"""
schools = {
'MIT': lambda: print("The school name is MIT"),
'HARVARD': lambda: print("The school name is HARVARD"),
'STANDFORD': lambda: print("The school name is STANDFORD")
}
try:
school_name = schools['MIT']
except KeyError:
raise Exception("Key error")
else:
school_name() # The school name is MIT
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment