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?
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:
...
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!!!
>>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With