Categories
Python Answers

How to catch multiple exceptions in one line with Python?

Spread the love

Sometimes, we want to catch multiple exceptions in one line with Python.

In this article, we’ll look at how to catch multiple exceptions in one line with Python.

How to catch multiple exceptions in one line with Python?

To catch multiple exceptions in one line with Python, we can separate the exceptions we want to catch with commas.

For instance, we write:

try:
    raise ValueError('Represents a hidden bug, do not catch this')
    raise TypeError('This is the exception you expect to handle')
except (ValueError, TypeError) as e:
    print(repr(e))

We catch both ValueError and TypeError with one except clause.

And we get the exception content with e.

Conclusion

To catch multiple exceptions in one line with Python, we can separate the exceptions we want to catch with commas.

Leave a Reply

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