Categories
Python Answers

How to write a try-except block that catches all exceptions with Python?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *