Exception Handling in C#
(Page 1 of 8 )
The fundamental thing that exceptions allow you to do is to separate the essential functionality from the error handling. ReadSource has come close to the ideal version we're all looking for, thanks to exceptions. Ironically, exceptions allow us to get close to this ideal version of ReadSource but at the same time prevent us from quite reaching it. The problem is that if an exception occurs after acquiring the resource but before releasing it then the release will not take place. The solution to this lost release problem depends on the language you're using. C# allows you to create user-defined struct types that live on the stack but does not allow struct destructors.
Painful Procedural Error Handling
In the absence of exceptions the classic way to handle errors is to intertwine your statements with error checks. For example:
public sealed
class Painful
{
...
private static char[] ReadSource(string filename)
{
FileInfo file = new FileInfo(filename);
if (errorCode == 2342) goto handler;
int length = (int)file.Length;
char[] source = new char[length];
if (errorCode == -734) goto handler;
TextReader reader = file.OpenText();
if (errorCode == 2664) goto handler;
reader.Read(source, 0, length);
if (errorCode == -5227) goto handler;
reader.Close();
Process(filename, source);
return source;
handler:
...
}
}
This style of programming is tedious, repetitive, awkward, complex, and obscures the essential functionality. And it's too easy to ignore errors (either deliberately or accidentally). There have to be better ways. And there are. But some are better than others.
Next: Separation of Concerns >>
More C# Articles
More By Jon Jagger