Sometimes, we want to write a try-except block that catches all exceptions with Python.
In this article, we’ll look at how to write a try-except block that catches all exceptions with Python.
How to write a try-except block that catches all exceptions with Python?
To write a try-except block that catches all exceptions with Python, we can catch the Exception exception with the except block.
For instance, we write
import traceback
import logging
try:
whatever()
except Exception as e:
logging.error(traceback.format_exc())
to catch any exceptions raised by the whatever function when it’s called.
Then we call logging.error to log the traceback of the exception.
Conclusion
To write a try-except block that catches all exceptions with Python, we can catch the Exception exception with the except block.