Memi.Reflection

Private members of memi's thoughts

Exceptions vs Error Codes

Ashish has posted about his dilemma - whether to throw Exceptions or return Error codes. (His post has disappeared since, for some unknow reason).

We encountered this dilemma also, especially from a developers that have strong background in VB6 (The Java ones had no problems with this).

I think that in order to make the reasonable choice, a clear definition of what is an exception is required.

IMHO, Excpetion is a situation when a piece of code encounters some unexpected problem while running, and couldn't accomplish its task. The emphasis on the “unexpected“ is important, because it eliminates some scenarios that, from first glance, may require throwing an exception, but I think they really shouldn't do that.

Error, in contrast, is a situation when a piece of code encounters an expected problem while running, and couldn't accomplish its task. Again, the emphasis is important. As strange as it may sound, there are expected problems that should be taken care of while running.

Let's look at a sample:

The read() method of the (SQL | OleDB)DataReader. This method returns either true or false. False is returned when there are no more rows to read from. If we'll stick only to the “can't accomplish task“ definition, then the method should throw something like EndOfDataException. But in this case an error code is in order, since this is a (very) expected situation. I mean, you did expect the data to come to its end finally, didn't you?

But - if the connection to the database was terminated suddenly, then this method will throw an exception, since this should not happen, and it is very unexpected (and unwelcome) situation.

If we utilize this definition, we'll find out that the performance penalty of throwing exceptions is insignificant. The application has encountered some unexpected error which it does not know how to handle, and the best thing to do now is write something to log file, close all resources, go to the nearest shelter and pray. Performance are really meaningless in this situation.

It's important to avoid using Exceptions as Flags - “Hey, something happened. Now tell us how to go on.“ For example, In Ashish disappearing post, the following code sample is written:

===========================================================

My application, a web-service reads a string column from the database. 50% of the time this string is a datetime, 50% it’s not. In .net 1.0 /1.1 it is easy for this to lead to code like the following..

 DateTime d = DateTime.MinValue;

Try

{

            D = DateTime.Parse( string );

}

Catch( InvalidCastExcpetion )

{

            // swallow

}

 Put this in a loop in a middle tier component ( say processing a recordset ), and load up the server. You’ll generate 1000s of exceptions per second in the asp.net wp, and can easily drop throughput by an order of magnitude. There are a number of internal and external applications I’ve seen coded exactly like this. It’s hard to argue with the correctness of the DateTime.Parse() implementation from a purist pov, but the ramifications can be a lot of money spent on additional hardware by the consumer of the api.

=========================================================================

Couldn't say it better. Again, Exceptions should be used ONLY when something unexpected happened, and the process (the logical one, not the physical) should stop.

There is another reason for not using error codes, and that's the Return Value Type dilemma. When talking about “Error Code”, it's usually a number (eg. -1) or some kind of String. Our method won't necessarily return this type. It may return DataSet, Date, Custom objects or anything else. If we would like to be able always to return error code, and we'll try to utilize it for every problem, even the unexpected ones, each and every function will have to have “Object” as its return type. Another alternative is to have another ByRef argument which will hold the error code, but this will mess up the code and add unnecessary cumbersomeness to the method's interface.

So, to coclude:

When a method has some pre-defined situations when it might won't be able to accomplish its task, it should return an Error Code.

When a method encounters some unexpected problem which prevents it to accomplish its task, it should throw an Exception.

All of the above is, of course, my own opinion, and this is the standard I've taught our developers.

I'll be happy to read your feedback on it.

Posted: May 20 2004, 12:20 PM by memi | with 13 comment(s)
Filed under:

Comments

Addy Santo said:

I totally agree. It can be summed up into one key rule: "never use exceptions for applicational logic or flow control".

If you expect something as part of the normal/semi-normal application flow, that should not be implemented using exception handling. Exceptions should be reserved for situations which are truly exceptional, ie. "someone yust yanked out the hard disk"
# May 20, 2004 11:00 AM

TrackBack said:

Exceptions vs. Error Codes
# August 25, 2004 7:21 AM

Neil Pullinger said:

Having every method return an object type means casting. A possible alternative is to define an error code property in your classes.

# August 15, 2007 4:38 AM

links for 2007-08-28 | IndianGeek said:

Pingback from  links for 2007-08-28 | IndianGeek

# August 28, 2007 7:23 PM

Rajesh said:

Hi,

In a ASP.NET project, if a business rule check fails, then by your explanation, I would need to return a error code. But how as a separate object or a hashtable

# April 20, 2008 11:24 AM

www.dvddecoderspro.com said:

Tip# 4– Remove Spyware from your PC. Nothing brings a fast computer to a slow crawl faster than annoying Spyware that installs itself on your PC without your permission. Not only is Spyware a pain in the@ to try and remove manually, but it can be used

# June 27, 2008 6:32 AM

avi dvd burning said:

I can’ t stand this machine anymore. Its too slow. Getting hard rebuilding over and over every day. Down to 3 gigs of free space too. Time to buy a new one. Anyone care to contribute with the‘ help Zac get a new PC so he can program his open source stuff

# July 1, 2008 5:42 PM

dvd decrypter software said:

I didn’ t really believe that error could be in the way of zipping the template package but I gave my idea a try: I unzipped the template that I had uploaded successfully, then I deleted the zip- package and zipped back the template- files I had unpacked

# July 8, 2008 7:06 AM

shrink dvd said:

Mondorescue backs up your GNU/ Linux server or workstation to tape, CD- R, CD- RW, DVD- R[ W], DVD R[ W], NFS or hard disk partition. In the event of catastrophic data loss, you will be able to restore all of your data[ or as much as you want], from bare

# July 19, 2008 10:10 AM

copy dvd movies said:

Best- Family- Info. com Articles And Reviews! Health, Home And Happiness… « A TONIC Guide to Home Gardening Using Perennial Garden Flowers in Gardening»

# July 24, 2008 4:23 AM

dvd copy decrypt said:

Send a message Subscribe to RSS feed Tell a friend Add to My MSN Add to Live.

# July 24, 2008 8:37 AM

Emerald said:

Give please. Misquotations are the only quotations that are never misquoted. Help me! I can not find sites on the: Large outdoor wall clock. I found only this - <a href="wall-clock.biz/.../">bulova clock mantel wall</a>. He is opposed to be always basic for hosting the man-made discovery out of a intelligent and light guilt of changing into a more digestive destruction, wall clock. Wall clock, when one is on the importance and there are sailors also, one can eliminate with antenna with the apothekeprezzo of the fir calculations in division. :-( Thanks in advance. Emerald from Islands.

# March 24, 2010 11:17 AM

RabunpaniaBep said:

Look at this - don't is masterful <a href=jkgih.co.cc/.../a> I fantasize so.  

hdt6dsj

# May 27, 2011 8:03 AM
Leave a Comment

(required) 

(required) 

(optional)

(required)