Errors
Reference:
Handling Errors
Sometimes our programs will encounter errors. In Python, we can use a try... except
block to handle these errors.
After running into an error for the first time, we should observe what type of error we are experiencing (e.g. KeyError
, IndexError
, DivisionByZeroError
, etc.).
Once we know what type of error we need to handle, we should wrap the problematic code inside the try
clause, and specify the known error type in the except
clause:
If we're not yet sure what type of error we're experiencing, we can temporarily catch all error classes that inherit from the base error class (Exception
), and once caught, we print the specific error's datatype to learn how to handle it:
Raising Errors
If we find the need to trigger our own errors to stop program execution (less common), we can use the raise
keyword followed by the type of error (e.g. ValueError
):
Defining and Raising Custom Errors
We can define our own errors if that's helpful, by inheriting a class from the base Exception
class (or preferably a more specific one):
Last updated