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. Deep C#Buy Now From Amazon Chapter List
Extra Material <ASIN:1871962714> <ASIN:B09FTLPTP9> 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. Try-catchThe 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. For example: int a=10; 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. For example: catch(DivideByZeroException) Notice that the catch clause now only handles exceptions of type DivideByZeroException. |
||||||
Last Updated ( Thursday, 12 March 2020 ) |