Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

which exception catches xxxx error in python

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?

like image 262
Berry Tsakala Avatar asked Jul 15 '09 11:07

Berry Tsakala


2 Answers

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:
    ...
like image 123
codeape Avatar answered Sep 28 '22 02:09

codeape


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!!!
>>> 
like image 37
Anurag Uniyal Avatar answered Sep 28 '22 02:09

Anurag Uniyal