Thursday, 12 January 2012

Need for Error Handling

   Picture this: You’re doing a demo of your application for a client and then all of a sudden as if proving Murphy’s Law, the inevitable happens. Boom! … Your client gets to see a dialog with cryptic messages indicating that your application has crashed. You certainly wish that such a thing should never ever happen, but that wish would hold true only in an ideal world. The truth however is that unforeseen errors are bound to happen, one way or another in spite of careful coding accompanied with fairly rigorous testing. Keeping this
in mind, we as developers need to adopt defensive coding strategies with effective error handling techniques to trap and handle errors and exceptions, and to provide the user with adequate information on the nature and cause of the error before exiting from the application when an unexpected error occurs.
   An Exception is an abnormal/exceptional/unexpected condition that disrupts the normal execution of an application. A distinction needs to be made between expected conditions and unexpected conditions. Say for example you are writing a very large file to the hard-disk, it’s imperative that you should first check the disk space first, since there could be an expected condition that the hard-disk might be low on space, such conditions are not ideal candidates that warrant exceptions to be thrown. But on the contrary, what if an
unexpected hard-disk hardware failure occurred while writing to the file - This is an ideal candidate that warrants exceptions to be thrown. Always remember that though exception handling is very important, judicious use of this feature should be made since there is a performance cost when you use it.
    Error and exception handling are a part and parcel of every good language, framework class library, or application and should form a part of your applications too right from the planning stages. The .NET Framework Class Library (FCL) and Common Language Runtime (CLR) provide a rich infrastructure to catch and handle exceptions. The CLR infrastructure is also designed for cross-language exception handling - What this means is that if a VB.NET component throws back an exception to a C# application that’s
consuming the component, the C# application will be able to catch the error and obtain rich error information on the error that has occurred. Through the rest of the tutorial, we’ll see how to catch and handle exceptions in the .NET framework using C# and VB.NET.