Deferred Error Handling in Python: Return instead of Raise

Lu Zhenna
4 min readOct 17, 2023

Summary

This article shows a different way of handling errors in Python — deferred error handling. If exceptions or errors were returned instead of raises, we don’t have to interrupt the program but still provide a solution for different scenarios.

Target Audience

Python beginners who are interested in deferred error handling and have to catch specific exceptions instead of throwing an error.

WARNING: This method is not recommended if you need to resolve errors as soon as possible. Please read the new post, Deferred Error Handling in Python: Logging Errors to File, for a cleaner way to defer error handling.

Please use this friendly link if you are blocked by a paywall.

Outline

  1. How to raise an error?
  2. How to return an error?
  3. Why return errors instead of raise?
  4. How to handle different error cases?
Photo by Brett Jordan on Unsplash
  1. How to raise an error?
def stepOne(name: str):
if isinstance(name, str):
print(f"Hello, my name is {name}.")
else:
raise TypeError(f"Expected a string, but got {type(name)}!")

--

--

Lu Zhenna

Data Scientist | Data Engineer | Cognitive Psychology and Neuroscience PhD | 🤝 Connect with me on https://www.linkedin.com/in/zhenna-lu/