Chris Hall
Chris Hall

Reputation: 931

"2nd hand" Exception Handling in Python

Is there a way to take exception handling output from an imported module and process it from the calling program? For example, I have an imported module that writes an HTTP exception

except urllib2.HTTPError, e:
   sys.stderr.write(str(e) + '\n')

If a 404 occurs, then the calling programing only sees the following:

HTTP Error 404: not found

Can this be taken as input without modifying the imported module? I would need to perform different tasks depending on the HTTP Error that is returned.

Upvotes: 1

Views: 71

Answers (1)

huu
huu

Reputation: 7472

If you can modify the imported module, raise the error in the except block like so:

except urllib2.HTTPError, e:
    sys.stderr.write(str(e) + '\n')
    raise e

Then in the calling program, catch the error and inspect it for the error code:

except urllib2.HTTPError, e:
    if e.code == 404:
        do_something_here()

Upvotes: 1

Related Questions