Recognitions:

## I hate error handling

Error handling obfuscates code. For someone reading your code, what your program does when there is an error is usually unimportant--at first they care only what it does when it works properly, and maybe later they'll come back to the errors, but understanding your error handling is a very low priority for someone reading your program. Furthermore it's ugly. Throwing a bunch of trys and catches into a neat, clean block of code completely ruins it, as well as probably tripling its length.

So what work has been done on separating error handling from code?
 PhysOrg.com science news on PhysOrg.com >> Galaxies fed by funnels of fuel>> The better to see you with: Scientists build record-setting metamaterial flat lens>> Google eyes emerging markets networks
 Recognitions: Gold Member Science Advisor Staff Emeritus There's not a whole lot that can be done theoretically. Some errors need to be detected and handled within the bowels of an otherwise very clean algorithm -- and the desire to maintain code locality means that that error-handling code needs to be inserted right there in the algorithm. You would not want it to be hidden in some separate file. On the other hand, it's best to handle errors at the highest level possible. If you can allow exceptions to propagate out of entire blocks of code, you should. There are only a couple of ways to really "separate" error handling code. Validation of arguments is a good way to clean things up -- put all your type- and bounds-checking up at the start of each block. The rest of your code can then tacitly assume no errors due to invalid inputs are possible. Also, contractual assertions can also be grouped together at the bottom of blocks of code. These contractual assertions pretty much just make sure the block above them did what it was intended to do. Both of these techniques require a very good design skills, though; few people outside of academia really write their code with such foresight. You might be interested in some of the "cleanroom" software engineering principles, which can be used to mathematically prove that code does what it's intended to do, and thus eliminates many of the possibilities of exceptions. They require a significant investment of labor, however. - Warren

Recognitions:
Gold Member
Homework Help
 Quote by chroot Both of these techniques require a very good design skills, though;
Yes, I think what you said is a good overview.

 Quote by chroot few people outside of academia really write their code with such foresight.
If would be my experience that very few people fresh out of school address the problem at all, let alone "with foresight"

Recognitions:
Gold Member
Staff Emeritus

## I hate error handling

 So what work has been done on separating error handling from code?
You can always look at it as a presentation issue. Use an editor that lets you fold away things that you don't want to look at.

(Admittedly, I've been unhappy with what folding I've seen available, but I haven't explored them much. Maybe you should make a project to invent a good editor with useful folding ability. )
 Recognitions: Science Advisor You know, you can have multiple catches per try. :) I actually like try/catch statements, they're better than checking for error conditions with if statements, for example.
 Recognitions: Science Advisor Yes, I was thinking along the lines of an editor feature. But some programmers prefer to work with plain text in a plain text editor--me not among them--so I was also wondering if anyone's done research on, maybe, applying an exception-handling "schema" to code that doesn't have error checking. I once talked to someone who had the opinion that error handling should not be used as program control--that it should be used for only the things you can't detect otherwise, because of the overhead of throwing and catching an exception. At the time I disagreed, on the grounds that I'd rather write the "mainstream" of my code, then toss in some easy error handling for the cases where it doesn't work. I still believe, in regard to both exceptions and "unusual cases," that code should be written as if it worked and then patched for the cases where it doesn't work. But I think that the patch should be external--that someone should be able to read only the mainstream of your code, which gives them the gist of what it does, and only afterwards read what happens in special cases. Also, thinking about this just now, separating special cases from "mainstream" code might help a programmer write the program, too. By separating special cases into a different section, it might enable the programmer to review the special cases as an entity all their own and decide whether any error is still unchecked more easily. I think that a clue towards making something like that happen is finding ways to restrict what "special-case" or exception code should be able to do.

Recognitions:
Gold Member
Staff Emeritus
 Quote by 0rthodontist But I think that the patch should be external--that someone should be able to read only the mainstream of your code, which gives them the gist of what it does, and only afterwards read what happens in special cases.
This is a very bad idea. You generally want to promote code locality -- you want everything involved in a single task to be in the same place, where it can all be read together.

Besides, there are so many distinct ways that a complex piece of code can fail that separating the error handling in the fashion you desire would make it extremely difficult for a reader to piece it all together.

What you want -- a program without any kind of interwoven exception handling -- is a pipe dream. There are ways to hide or minimize the error handling, using editor features or design techniques like contracts. There are zero-defect techniques that can be used to formally prove that a piece of code has no exceptions which need to be handled -- but you want to be able to look at an arbitrary piece of complex code, written without the burden of formal verification -- without any of the "clutter" of error handling.

I think this is a pipe dream, because what truly separates a good programmer from an excellent programmer is his/her awareness of the failure modes of each line of code written. A programmer who intends to write a piece of code as if nothing can go wrong, and only later go in and "insert" error handling as an afterthought, is a poor programmer.

- Warren
 Recognitions: Science Advisor Nonsense--planning the main idea of your code first before writing the special cases is just another incarnation of top down design. It is a good idea to focus on the big picture before worrying about the details. This goes when you're writing code as well as when you're reading it. Why not reflect that as a language feature? I agree that repeatedly referring to an outside section of code for exception handling is a bad idea. The challenge would be to make the syntax for an exception handling schema simple and clear enough so that you can read it once and don't often need to refer back to it, but powerful enough so that it can do the things it needs to do. I don't believe that failure modes of a particular line of code is a high priority. It's certainly important, but it's secondary. Understanding how the code actually works, when it does work, is the essential step 1 for making or reading it. Surely you are not proposing that it is more important, on a first reading, to understand the 1% of the time when flawed code fails than the 99% when it works? Even if your goal is to fix the flawed code, do you really want to look at the failures before you understand how the program's even intended to run? There is another advantage to separating exceptions and special cases from the mainstream code: doing so promotes the concept of exceptions and special cases. It creates a clear, abstract distinction between exceptions and special cases, and the main code. A change to code can then be looked at as either a "special case" alteration, or a "mainstream" alteration. Special cases tend to be local and trivial, and easier to change without affecting mainstream code. Mainstream code, being the actual design of the application, is much harder to change, and the programmer should be aware of which he is dealing with at a given time. Separating special cases introduces that abstraction.
 Recognitions: Gold Member Science Advisor Staff Emeritus I posit that writing code is considerably more important than reading code.
 Recognitions: Gold Member Science Advisor Staff Emeritus I mean no offense, Orthodontist, but you're a student, right? It seems every student goes through a phase where they think they can design a better language... - Warren
 I don't understand where your issue with readability in error-handling applies. In the function, raising the error will be very clean, and actually provide insight in to the limitations/restraints/and conditions of the procedure, hence more readable code. On the other hand, in the implementation where some obfuscation may occur, as an error excepting handle appears for every function call... this all occurs to the extent of the programmer's needs. If it ever becomes obfuscated beyond the point of readability, either it's complicated enough to disregard the possibility of language-related syntactical anomalies, or the programmer who's implementing the functions is being redundant or over-protective of the performance of his code. All in all, I think it's silly to be pestering about this.
 Recognitions: Science Advisor I agree with Sane on this.

Recognitions:
 Quote by Hurkyl Ipositthatwritingcodeisconsiderablymoreimportantthanreadingcode.
Itisatruefactthatmostprogrammingworkiscodemaintenance,notcreation.

 Quote by chroot Imeannooffense,Orthodontist,butyou'reastudent,right?Itseemseverystudentgoesthroughaphasewheretheythinktheycandesignabetterlanguage...
Idon'tthinkit'saverycommoninterest.Anywaytherearealotoflanguages,andalotoffairlynewlanguages,soit'snotanunrealisticgoal.

Considerthefollowingfunction,notwrittenbyme:
Code:
        defwget_link(self,url,flag,parent_url="",ignore_pr=False):
"""
Downloadurlandallrequisitepages
FirstCreatenewdiroruseoldparentdir
"""
dir=md5dir(self.subdir,url,parent_url)
ifdir==None:
print'md5dircamebackwithnone!'
sys.exit()
#print"\twgetting%s"%url

#Retrievalofimagesfromyahoodoesn'tusetheprinterreadyflag,htmldoes
ifignore_pr:
pr=''
wget_command=('/usr/bin/wget-E-nv-H-k-p%s--no-host-directories--no-directories-P%s\"%s%s\"'%(flag,dir,url,pr))
(status,output)=commands.getstatusoutput(wget_command)
if(status>0):
self.pr("Wgetfailed!\n\t%s"%output)
return()
#seewhatwgetrenamedthefileas
try:
link=output.split('URL:')[1]
except:
self.pr("WGETERROR:\ncommand:\n%s\nURL:%s\n--\n%s\n--\nCouldnotdeterminenewwgetlink:%s"%(wget_command,url,output,sys.exc_info()[0]))
return('')
Consideritsequivalentwithnoerrorchecking:
Code:
        defwget_link(self,url,flag,parent_url="",ignore_pr=False):
"""
Downloadurlandallrequisitepages
FirstCreatenewdiroruseoldparentdir
"""
dir=md5dir(self.subdir,url,parent_url)

#Retrievalofimagesfromyahoodoesn'tusetheprinterreadyflag,htmldoes
wget_command=('/usr/bin/wget-E-nv-H-k-p%s--no-host-directories--no-directories-P%s\"%s%s\"'%(flag,dir,url,pr))
(status,output)=commands.getstatusoutput(wget_command)
#seewhatwgetrenamedthefileas
link=output.split('URL:')[1]
return(link)
It'sclearer.Actuallytheessenceofthisfunctioncouldbe2lineswithouterrorcheckingandifyouaskthecallertomakethedirectory,namelyjustawgetandareturnoftheURL,vastlyreducingthetimeneededtofigureoutwhatthehellisgoingon.Alsoyoureallyonlyneed2arguments,dirandurl,not4.
 Recognitions: Science Advisor Why can't I edit? Edit: I mean, why can't I post any Python code? Edit: I can if I replace the spaces with ededed-colored 's...
 Recognitions: Science Advisor It would be a bit clearer if the type of the error were included, but that's not the main problem. Consider this function: Code:  def retrieve (self): try: mod=self.current.modified except: mod='' self.new = feedparser.parse(self.url,modified=mod) try: if self.new.status == 304: self.pr ('\t304: no updates') return() except: self.pr('No status variable... no internet access?') self.new.status=304 return() if self.new.bozo>0: self.pr('Failed to retrieve (proper) rss feed:\n\t%s' % (self.new.bozo_exception)) if self.new.feed.has_key('lastbuilddate'): try: self.new.lbd = time.strptime(self.new.feed['lastbuilddate'],"%a, %d %b %Y %H:%M:%S %Z") self.pr('LBD of new feed %s' % (time.mktime(self.new.lbd))) except: pass else: try: if time.mktime(self.current.lbd) == time.mktime(self.new.lbd): self.pr ('\tLBD unchanged %s==%s' % (time.mktime(self.current.lbd),time.mktime(self.new.lbd))) self.new.status=304 return() except: self.pr ('\tNo LBD key in current: %s' % sys.exc_info()[0]) #self.pr ('\tstatus: %d ' % self.new.status) self.pr ('\tEntries retrieved: %d' % len(self.new.entries)) # number the entries for renaming the link in the updates subroutine ind=0 for x in self.new.entries: x.index=ind ind+=1` Without error handling (and removing some extraneous code), this is one line (whited out so you can read the function as written first): return feedparser.parse(self.url,modified=mod) Is it easier to understand if you see that one line, or see all the error handling?