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
- How to
raise
an error? - How to
return
an error? - Why
return
errors instead ofraise
? - How to handle different error cases?
- 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)}!")