5

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?

3 Answers 3

4

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:
    ...
Sign up to request clarification or add additional context in comments.

Comments

3

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!!!
>>> 

Comments

0

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.

1 Comment

-1 He's NOT raising it, the httplib module is raising it. Debugging 101, Lesson 1: read the traceback carefully.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.