Thread Closed

I hate error handling

 
Share Thread Thread Tools
Nov6-06, 12:54 AM   #1
 
Recognitions:
Science Advisor Science Advisor

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
PhysOrg
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
Nov6-06, 02:21 AM   #2
 
Recognitions:
Gold Membership Gold Member
Science Advisor Science Advisor
Retired Staff 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
Nov6-06, 11:59 AM   #3
 
Recognitions:
Gold Membership Gold Member
Homework Helper Homework Help
Science Advisor Science Advisor
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"
Nov6-06, 12:28 PM   #4
 
Recognitions:
Gold Membership Gold Member
Science Advisor Science Advisor
Retired Staff 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. )
Nov6-06, 06:58 PM   #5
 
Recognitions:
Science Advisor 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.
Nov7-06, 07:16 PM   #6
 
Recognitions:
Science Advisor 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.
Nov7-06, 07:28 PM   #7
 
Recognitions:
Gold Membership Gold Member
Science Advisor Science Advisor
Retired Staff 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
Nov7-06, 08:14 PM   #8
 
Recognitions:
Science Advisor 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.
Nov7-06, 09:09 PM   #9
 
Recognitions:
Gold Membership Gold Member
Science Advisor Science Advisor
Retired Staff Staff Emeritus
I posit that writing code is considerably more important than reading code.
Nov7-06, 09:36 PM   #10
 
Recognitions:
Gold Membership Gold Member
Science Advisor Science Advisor
Retired Staff 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
Nov7-06, 09:48 PM   #11
 
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.
Nov8-06, 07:28 AM   #12
 
Recognitions:
Science Advisor Science Advisor
I agree with Sane on this.
Nov8-06, 02:28 PM   #13
 
Recognitions:
Science Advisor Science Advisor
Quote by Hurkyl
I`posit`that`writing`code`is`considerably`more`important`than`reading`code.
It`is`a`true`fact`that`most`programming`work`is`code`maintenance,`not`creation.

Quote by chroot
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...
I`don't`think`it's`a`very`common`interest.``Anyway`there`are`a`lot`of`languages,`and`a`lot`of`fairly`new`languages,`so`it's`not`an`unrealistic`goal.

Consider`the`following`function,`not`written`by`me:
Code:
        def`wget_link(self,url,flag,parent_url="",ignore_pr=False):
                """
                Download`url`and`all`requisite`pages
                First`Create`new`dir`or`use`old`parent`dir
                """
                dir=md5dir(self.subdir,url,parent_url)
                if`dir==None:
                        print`'md5dir`came`back`with`none!'
                        sys.exit()
                #print`"\twgetting`%s"`%`url

                #`Retrieval`of`images`from`yahoo`doesn't`use`the`printer`ready`flag,`html`does
                pr=self.printer_ready
                if`ignore_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`("Wget`failed!`\n\t%s"`%`output)
                        return()
                #`see`what`wget`renamed`the`file`as
                try:
                        link=output.split('`URL:')[1]
                        link=link.split('"')[1]
                        return(link)
                except:
                        self.pr`("WGET`ERROR:\ncommand:\n%s\nURL:%s\n--\n%s\n--\nCould`not`determine`new`wget`link:`%s"`%`(wget_command,url,output,sys.exc_info()[0]))
                        return('')
Consider`its`equivalent`with`no`error`checking:
Code:
        def`wget_link(self,url,flag,parent_url="",ignore_pr=False):
                """
                Download`url`and`all`requisite`pages
                First`Create`new`dir`or`use`old`parent`dir
                """
                dir=md5dir(self.subdir,url,parent_url)

                #`Retrieval`of`images`from`yahoo`doesn't`use`the`printer`ready`flag,`html`does
                pr=self.printer_ready
                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)
                #`see`what`wget`renamed`the`file`as
                link=output.split('`URL:')[1]
                link=link.split('"')[1]
                return(link)
It's`clearer.``Actually`the`essence`of`this`function`could`be`2`lines`without`error`checking`and`if`you`ask`the`caller`to`make`the`directory,`namely`just`a`wget`and`a`return`of`the`URL,`vastly`reducing`the`time`needed`to`figure`out`what`the`hell`is`going`on.``Also`you`really`only`need`2`arguments,`dir`and`url,`not`4.
Nov8-06, 02:56 PM   #14
 
Recognitions:
Science Advisor 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...
Nov8-06, 03:40 PM   #15
 
Now yet again, you are splitting hairs ...

Focusing on that Python code you posted, that is a poor example to prove a point. The error handling is not filtering what kind of error it handles. Using the except command without any statement following it will direct any error to the excepted code block.

If the code were written properly, it would be clear and concise as to what error it's excepting and handling. This is definitely more readable. To think otherwise is either ignorant, or just plain silly.
Nov8-06, 05:00 PM   #16
 
Recognitions:
Science Advisor 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?
Nov8-06, 05:08 PM   #17
 
Recognitions:
Gold Membership Gold Member
Science Advisor Science Advisor
Retired Staff Staff Emeritus
So... why doesn't the author just put that "one-liner" in his comments above the code? Then you know exactly what the "gist" of the block is -- that's what this is all about, right? -- and the error-handling code stays put, interwoven with the code it protects, as it should be.

And, besides, the code you pasted does NOT just download a page -- it checks server status codes, timestamps, and does other things. I agree it's poorly written code, but even without error-handling, it won't be just one line. You're being dishonest.

- Warren
Thread Closed
Thread Tools


Similar Threads for: I hate error handling
Thread Forum Replies
Exception Handling Programming & Comp Sci 7
Data handling Introductory Physics Homework 1
I hate chemistry! Hate it! Hate it! Hate it! General Discussion 48
Question about handling General Engineering 1
NAN handling in C Computing & Technology 5