Lesson 27. Error Handling
Practically all of the lessons in this tutorial do not use any error handling. This is for pedagogical reasons. In reality, you need to write your code in a robust way so it can handle errors gracefully.
Sources of errors include but are not limited to:
Database servers down
Network errors
Web servers down
Accessing directories and files that do not exist
Bad user input
That dude from the Allstate commercials
Gremlins. Not a joke.
Python, like many languages, implements error handling through the try/catch paradigm.
Try Catch Syntax
Examples
Example #1: Basic Error Handling Hello World
Every error handling example starts with a divide by zero error.
Example #2: Using Built-in Exceptions
You can catch errors by using the Exception class, but if you really want to get fancy, you can catch specific errors. Catching errors this way allows you to develop gentler error messages than the intimidating trace you’d normally get with a bare error.
A list of built-in exceptions can be found here.
Example #3: Using Exceptions In Modules
Finally, modules also come with exceptions.
Now you try it!
Don't copy and past. Type the code yourself!
Last updated