Python Error Handling
Raising an exception
def myFunc(myParam):
if myParam > 365:
raise Exception("Error: input must be 365 or less")
myFunc(500)
- By raising an exception, you can cause the code to crash and indicate the error if an unacceptable condition is met.
Asserts
assert myParam > 365, "Error: input must be 365 or less"
- An assert is a quick way to check if a condition is met, otherwise it will raise an AssertionError exception with the specified error.
- It is optional to specify the error text, but you must not have a comma if you don't include the text.
Handling exceptions
try:
myFunc(500)
except:
# Code to execute in response
- If any code in the 'try' area fails with an Exception, the program will execute the code in the 'except' area.
- Some functions from built-in or external Python libraries can throw exceptions, so you may want to hande them.
Handling and displaying exception error
try:
myFunc(500)
except Exception as e:
# Code to execute in response
print(e)
- The description of the exception will be stored in the variable 'e' which can be displayed.
Responding to known exception types
try:
myVar = 12 * "hi"
except TypeError as e:
# Response for TypeError exception
print(e)
except Exception as e:
# Response for all other exceptions
print(e)
- You can check for different error types and respond differently to each one.
- You can find a list of exception types online.
Printing a stack trace (path of function calls to error)
import traceback
try:
myFunc()
except Exception:
traceback.print_exc()
- This shows the error and path to it as it would if the exception had not been handled, but you can also add code to handle it.
Challenge
Write a function that will divide two numbers and have it display a warning message and return 0 if a ZeroDivisionError exception is found. If any other exception is found, have it print "Something went wrong" and display the error stack trace.
Completed