[Tutor] Handling exceptions

Steven D'Aprano steve at pearwood.info
Mon Nov 7 17:01:15 CET 2011


Gerhardus Geldenhuis wrote:

>   try:
>     server = xmlrpclib.Server("http://192.168.2.11/cobbler_api")
>     #...
>   except xmlrpclib.Fault as detail:
> 
>     print 'xmlrpc error'
>     print detail
> #    print detail.arguments
>     print repr(detail)
> 
> I don't understand what I am getting from the exception. Do I only get a
> string and is the above snippet a good/clean/nice way of handling it. If I
> only get a string then it is likely that I will have to have  few if's to
> handle the various error strings returned.

No, that is the wrong way of handling exceptions.

You should not catch exceptions only to print them. (Actually, there are 
a few times where it *is* appropriate to catch and print exceptions by 
hand, as you have done, but they are rare.)

In general, the only reason to catch an exception is to recover from it, 
then to proceed. E.g. "if it fails, try something different".

In the above, you don't recover from the failure to connect to the 
server. You print some diagnostic information, but then your code tries 
to continue without a defined server.

(If your code above is only for experimentation, that's fine.)

If you aren't able to recover from an exception, normally the right 
thing to do is... just don't catch it at all. In this case, just write this:

server = xmlrpclib.Server("http://192.168.2.11/cobbler_api")

without a try...except block, and if an exception is raised, you will 
get a traceback automatically printed showing you:

* the type of error
* an error message
* the line number of the code that failed
* the full stack trace of each operation leading up to the error


Learning to read stack traces is not hard, but it is absolutely vital to 
being a good Python coder.


In particular, you should never programmatically make decisions about an 
error based on the error message:


# Don't do this!
try:
     x = mylist.index(None)
except ValueError as e:
     if e.message == "x not in list":
         process_failure()


The problem is that the error message is not part of the promised 
interface of the language. It could change suddenly, without warning, at 
any time. Just because the message is "x not in list" today, doesn't 
mean it will be tomorrow, or next week, or in two minutes. The only 
promise being made is that the error message will be useful to a human 
reader (or at least, it *should* be useful). The exact wording is 
certainly not promised, and so cannot be relied upon.



-- 
Steven


More information about the Tutor mailing list