Python Catch Multiple Exceptions With Examples

We can use a try-except block to catch exceptions and process them. Sometimes we call a function that may throw multiple types of exceptions depending on the arguments, processing logic etc. In this tutorial, we will learn how to catch multiple exceptions in python.

Python Catch Multiple Exceptions

Let’s say we have a function defined as follows:

We can catch both ValueError and TypeError in different except block.

I have put the try-except block in while True loop so that I can run the scenario of catching multiple exceptions.


Catch Multiple Exceptions in a single except block

If you notice the except block code, it’s same for both the exception types. If that is the case, we can remove the code redundancy by passing the tuple of exception types in the except block.

Here is the rewrite of above code where we are catching multiple exceptions in a single except block.

The output will be exactly the same as earlier. We can use this approach when the code in except block is the same for multiple exceptions being caught.

You can checkout complete python script and more Python examples from our GitHub Repository.

By admin

Leave a Reply

%d bloggers like this: