Python language basics 59: catching multiple exception types
October 31, 2015 2 Comments
In the previous post we looked at how to handle exceptions in python. The most important keywords you’ll need to know of are “try” and “except”. We saw how code execution stops at the point where the exception is raised. It continues on the first line of a matching except-block, i.e. which handles just that type of exception that was raised.
This short post shows a little trick if you want to handle different types of exception in the same way.
Multiple error types
We actually saw an example of catching multiple exception types in the previous post:
try: //some code except KeyError: print("This capital doesn't figure in the collection") except ZeroDivisionError: print("Errr..., what are you doing???")
What if you want to carry out the same exception handling logic irrespective of the exception type? You could write like this:
try: //some code except KeyError: print("Incorrect") except ZeroDivisionError: print("Incorrect")
However, it’s futile, as the same logic is duplicated in the two different places. You can solve the issue as follows:
except (KeyError, ZeroDivisionError): print("Incorrect")
You can just list the different exception types and separate them by a comma in parenthesis.
In case you’d like to handle any type of exception then you’ll find several tips on the internet, such as this thread:
except Exception: print("Exception")
However, you should not overuse this in real code. Always try to catch specific exceptions first and only then have a generic exception handling block so that your application doesn’t just exit unexpectedly.
Read the next part here.
Read all Python-related posts on this blog here.