Ned Batchelder: Exceptions vs. status returns
Broadly speaking, there are two ways to handle errors as they pass from layer to layer in software: throwing exceptions and returning status codes. Almost everyone agrees that exceptions are the better way to do it, but some people still prefer status returns. This article shows why exceptions are better.
I've been thinking about the issue some lately, as I've been annoyed that Python's (and Ruby's... haven't tried Perl's for this) FTP library throws exceptions in places where just a return value might be easier to deal with... For instance, I want to change to a directory on an FTP server, but if the directory doesn't exist, create it. To me, something like:
if not ftp.cwd(settings['remote-dir']):
print "Couldn't change to directory (",e,").
Making directory",settings['remote-dir']
if not ftp.mkd(settings['remote-dir']):
print "Error, couldn't make directory:", e
ftp.close()
sys.exit(1)
else:
ftp.cwd(settings['remote-dir'])
is much easier than:
try:
print ftp.cwd(settings['remote-dir'])
except ftplib.error_perm, e:
try:
print "Couldn't change to directory (",e,").
Making directory",settings['remote-dir']
ftp.mkd(settings['remote-dir'])
except e:
print "Error, couldn't make directory:", e
ftp.close()
sys.exit(1)
else:
ftp.cwd(settings['remote-dir'])
(code reformatted a bit to fit)
Not a great example, and maybe exceptions are better even in this case because they'll kill your program if the second "cwd" fails so you won't be working in an inconsistent state.
Anyway, just thinking out loud... I'm not totally comfortable with exceptions since I didn't "grow up" using them. I'd write more or think more... but I gotta get to bed.
Feel free to post a comment below. Please see my comment policy.
Formatting Rules (No HTML):