What exception catches xxxx error in python

given the trace error log, I don't always know how to catch a specific exception.

my question in general is how to determine which "except" clause needs to be written to handle a specific 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(...)

The capture of the second example is obvious:

try:
    ...
except UnicodeDecodeError:
    ...

How will I definitely catch the first mistake?

+5
source share
3 answers

Look at the stack trace. The caller of exception raise socket.error, msg.

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

import socket
...
try:
    ...
except socket.error:
    ...
+4
source

The first is also obvious, as the second, for example,

>>> try:
...     socket.socket().connect(("0.0.0.0", 0))
... except socket.error:
...     print "socket error!!!"
... 
socket error!!!
>>> 
+3
source

, , , . , , , .

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

But for another such exception, you either have to wait until it is thrown to find where the class is, or you need to read the documentation to find out where it comes from.

0
source

All Articles