Menu Close

How to use Python try…except as in except?

Sometimes, we want to use Python try…except as in except.

In this article, we’ll look at how to use Python try…except as in except.

How to use Python try…except as in except?

To use Python try…except as in except, we use as to assign the exception thrown to a variable.

For instance, we write

try:
    # ...
except (Exception1, Exception2) as e
    print('error')

to catch instances of Exception1 and Exception2 and assign the exception instance to e in the except block.

Conclusion

To use Python try…except as in except, we use as to assign the exception thrown to a variable.

Posted in Python, Python Answers