views:

241

answers:

3

Thanks! the question is solved in all the answers given.

Original question follows:

given a traceback error log, i don't always know how to catch a particular exception.

my question is in general, how do i determine which "except" clause to write in order to handle a certain exception.

example 1:

  File "c:\programs\python\lib\httplib.py", line 683, in connect
    raise socket.error, msg
error: (10065, 'No route to host')

example 2:

return codecs.charmap_encode(input,errors,encoding_table)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xd7 in position(...)

catching the 2nd example is obvious:

try:
    ...
except UnicodeDecodeError:
    ...

how do i catch specifically the first error?

+2  A: 

Look at the stack trace. The code that raises the exception is: raise socket.error, msg.

So the answer to your question is: You have to catch socket.error.

import socket
...
try:
    ...
except socket.error:
    ...
codeape
+2  A: 

When you have an exception that unique to a module you simply have to use the same class used to raise it. Here you have the advantage because you already know where the exception class is because you're raising it.

try:
    raise socket.error, msg
except socket.error, (value, message):
    # O no!

But for other such exception you either have to wait until it gets thrown to find where the class is, or you have to read through the documentation to find out where it is coming from.

Robbie
A: 

First one is also obvious, as second one e.g.

>>> try:
...     socket.socket().connect(("0.0.0.0", 0))
... except socket.error:
...     print "socket error!!!"
... 
socket error!!!
>>>
Anurag Uniyal