In this article, we will look into handling errors in an optimistic way. Handling of errors is quite common task in any kind of programming language. Most of the modern languages like C++, C# uses similar kind of exception handling constructs. We will see how to handle exceptions without any performance impact on the application by examples. I will be using VS 2008 with C# as language for all the samples.Exception Handling helps us to create robust and secure applications at a performance loss. So, we need to be careful in handling the exceptions. Always remember that throwing and catching exceptions is of high cost. So use exceptions to handle unexpected scenarios. Don't use exceptions for handling invalid data or to control the flow of code. Use finally block to release resources irrespective of error occurrence. Handle all kinds of invalid data using validations instead of exceptions. Try to handle all kind of exceptions for a better logging. Don't handle all kind of exceptions using single generic catch block. Don't throw/re-throw exceptions unnecessarily. Throw the exceptions that you can handle. Use performance counters to estimate the impact of exceptions on application performance in terms of number of exceptions thrown/caught. Use "using" block to release the resources immediately without the need of try/finally block. Let's touch all the above scenarios with an example. Create a console application named as ExceptionHndPractice.
I hold Bachelors degree in Computer Science along with MCSD,MCTS and MVP for the year 2009. Areas of Interest: C#, WPF, WF, silverlight, ASP.NET, Oracle and SQL Server.
C# Corner. All contents are copyright of their authors.