|Deep C# - Take Exception to Everything|
|Written by Mike James|
|Thursday, 12 March 2020|
Page 1 of 5
Structured exception handling sounds like a really good idea until you start to look at it more closely - then it almost becomes worse than the problem it is trying to solve. We look at exception handling - the philosophy, the strategy and the way C# does the job.
Once upon a time we wrote programs that worked and they were designed not to crash.
Of course this is a fairy story and what we actually did was to write programs that worked as long as nothing unusual happened - that is as long as the input and operating conditions were as "expected" by the programmer.
If this wasn’t the case well - what could you expect - the program was broken and beyond our control. The runtime system generally ended the program with an "abnormal end" or "abend".
Of course today this would be a ridiculous way to handle errors but programs still fail at runtime because eliminating runtime errors is still usually something of an afterthought.
The solution to the problem is generally accepted to be structured exception handling - that is try-catch to you and me. However the whole subject is trickier than you might imagine.
Let's take a look at how it all works and how it all might be made to work.
The basic syntax and operation of exception handling is very simple.
You surround any block of code that you think might fail with a try clause. If something does go wrong the block of code generates, or throws, an exception which is caught by the catch clause.
In this case it is clear that b is zero and so a/b cannot be computed and so the CLR throws a runtime exception. This is caught by the catch clause and the message is displayed.
This is a very common way to use the try-catch but it has a problem.
Suppose the exception is caused by something other than a divide by zero error. The catch clause operates no matter what the problem is with the try block leading the user and the programmer trying to fix the problem to believe that it is a division by zero problem. The solution is to always specify what exception you are handling with a conditional catch clause.
Notice that the catch clause now only handles exceptions of type DivideByZeroException.
|Last Updated ( Thursday, 12 March 2020 )|