Hacker News new | ask | show | jobs
by hntester123 5009 days ago
That's an interesting idea: to only catch exceptions at a very high level (for fast prototyping). I tried it out with this test program:

http://pastie.org/4791686

Though it works, one potential issue I found with it is that it does not give enough context as to where in the program the exception occurred. E.g. if I have more than one open() call (all for read mode) in the code, it will give the same error message for an exception occurring on any of those open() calls (as long as the exceptions all happen for the same underlying reason, such as "file not found". E.g.:

Exception occurred: IOError(2, 'No such file or directory')

Had you come across this and found any way to handle it? I though of passing some unique code for each case, but there seems to be no way to do it, because we are not calling the except clause ourselves - Python does it.

Edit: just thought of a (crude) way to handle that issue: declare a global variable, say, "location", and set it to a different numeric or string value at each place in the code where an exception may be thrown, or at least at one place, say the top of the function, in each function or method. And then in the single except clause, print the value:

print "location=", location

This will at least help narrow down the area of code in which the exception was thrown.

1 comments

Huh? Most languages with exceptions provide stack traces, so you can find which function (and line) caused the exception and also what functions were called up to the function that caused the exception. This makes it pretty easy to find out which call to open() caused the exception.
Heck, I commented in a hurry without thinking :( I did know about stack traces (used so many times), and you're right, of course. Thanks for pointing it out, though :). Now that I think of it more, since stack traces exist, there isn't even a need for that top-level try/except, for early prototypes. You can just write your main code, run it and let it fail, and fix the errors as you find them, by using try/except/finally etc.
Yep.

I use the high-level error handler to let me know when a failure has some impact besides dumping a stack trace on my screen. E.g., failed web request, batch job barfing, etc. And to present the user with some reasonable "we're on it" thing.

Clear, and a good idea. Thanks.