Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it reasonable in Python to check for a specific type of exception using isinstance?

Is it reasonable in Python to catch a generic exception, then use isinstance() to detect the specific type of exception in order to handle it appropriately?

I'm playing around with the dnspython toolkit at the moment, which has a range of exceptions for things like a timeout, an NXDOMAIN response, etc. These exceptions are subclasses of dns.exception.DNSException, so I am wondering if it's reasonable, or pythonic, to catch DNSException then check for a specific exception with isinstance().

e.g.

try:
    answers = dns.resolver.query(args.host)
except dns.exception.DNSException as e:
    if isinstance(e, dns.resolver.NXDOMAIN):
        print "No such domain %s" % args.host
    elif isinstance(e, dns.resolver.Timeout):
        print "Timed out while resolving %s" % args.host
    else:
        print "Unhandled exception"

I'm new to Python so be gentle!

like image 553
Vortura Avatar asked Feb 11 '12 23:02

Vortura


People also ask

How do you check for specific exceptions in Python?

In Python, exceptions can be handled using a try statement. The critical operation which can raise an exception is placed inside the try clause. The code that handles the exceptions is written in the except clause.

When would you use a try or expect block?

The try block lets you test a block of code for errors. The except block lets you handle the error. The else block lets you execute code when there is no error. The finally block lets you execute code, regardless of the result of the try- and except blocks.


1 Answers

That's what multiple except clauses are for:

try:
    answers = dns.resolver.query(args.host)
except dns.resolver.NXDOMAIN:
    print "No such domain %s" % args.host
except dns.resolver.Timeout:
    print "Timed out while resolving %s" % args.host
except dns.exception.DNSException:
    print "Unhandled exception"

Be careful about the order of the clauses: The first matching clause will be taken, so move the check for the superclass to the end.

like image 112
Sven Marnach Avatar answered Nov 12 '22 15:11

Sven Marnach