Member-only story
Handling Errors in Python
Best practices for gracefully handling errors in Python

“The greatest mistake is to imagine that we never err.” — Thomas Carlyle
Adding extensive error handling is crucial when developing maintainable and robust code. Errors can fall into several categories: logical errors, generated errors, compile-time errors, and runtime errors. In this article, we’ll focus on handling runtime errors — errors that occur while a program is running.
Why Do We Need Error Handling?
1. Prevents program from crashing if an error occurs
- If an error occurs in a program, we don’t want the program to unexpectedly crash on the user. Instead, error handling can be used to notify the user of why the error occurred and gracefully exit the process that caused the error.
2. Saves time debugging errors
- Following reason #1, having the program display an error instead of immediately crashing will save a lot of time when debugging errors.
- The logic inside the error handler can be updated to display useful information for the developer, such as the code trackback, type of error, etc.
3. Helps define requirements for the program
- If the program crashes due to bad input, the error handler could notify the user of why the error occurred and define the requirements and constraints of the program.
Error-Handling Practices
In this article we’ll discuss the following:
- Exception handling using
try - except
andtry - except - finally
- Assertions
- When to use exceptions vs. assertions
You will thank yourself later if you apply these error-handling techniques.