[Tutor] try..except - what about that ton of **Error statements?

Steven D'Aprano steve at pearwood.info
Wed May 22 15:07:53 CEST 2013


On 22/05/13 16:20, Jim Mooney wrote:
>> Keep the try block small. For example if it's for a call to
>> open(filename, "r") the only possible errors (assuming correct syntax)
>> are NameError for using an undefined variable and IOError for
>> specifying a file which doesnt exist.


Jim, I don't know who you are replying to here. You have quoted somebody, but not included an attribution. Whoever it was that replied to you, I don't seem to have their email (maybe they sent it direct to you, not to the list?) so I have no idea who it was.

However, let me say that under normal circumstances, you should not catch NameError. A NameError is almost always a programming error: you have made a typo, or tried using a variable that doesn't exist. You need to see that error, so you can fix it, not just hide it with a try...except.

A very important quote from Chris Smith:

"I find it amusing when novice programmers believe their main job is preventing programs from crashing. ... More experienced programmers realize that correct code is great, code that crashes could use improvement, but incorrect code that doesn't crash is a horrible nightmare."

In the specific case of the open command, there are many other errors that can occur:

IOError, if the file doesn't exist, or is unreadable, or if you do not have read permission, or any one of a number of rarer file-system errors;

TypeError, if the file name contains an ASCII NULL character, or if you pass something other than a file name;

TypeError again, if you pass too few, or too many, arguments;

ValueError, if you provide an illegal mode argument (e.g. 'x' instead of 'r' or 'w');

to mention only a few. But nearly all of them are programming errors, and should not be caught, they should be fixed. E.g. if you get a NameError, *fix the typo*. If you get ValueError, *use a legal mode*. And so forth. IOError is probably the only one you might legitimately want to catch, and even then only if you can recover from the error.


-- 
Steven


More information about the Tutor mailing list