Exceptions vs Error Codes (异常还是错误代码)

 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.

posted on 2008-01-16 13:44  Wind Snail  阅读(747)  评论(1编辑  收藏  举报

导航