Python Error Handling

Raise 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

Handle 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

Handle and Display 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 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