Here I would like to explain a bit about one of the best practices in application error handling or exception handling in C#. Normally an exception is raised when a runtime error or an unexpected condition is incurred. So, how to deal with this kind of situations? Whether to trap it in each and every situation (method) you handle? What is the need and use of different exception types?
The answer is, you should trap an exception (By writing the try… catch block) only if you are expecting some particular type of exception for which you know the reason. So that you can rectify and come out of the situation which causing the exception
The other situation is like you have to add some more information to the exception object or you want to wrap the exception caused with some another type and re-throw a different kind of exception.
Don’t ever try to simply catch the exceptions about which you don’t know anything or want to do nothing, but just a re-throw.
Always try to use a much similar or exact exception type which you are expecting and try to stop using the base “Exception” class in each and every situation. For instance if you use SQLexception to catch errors while interacting with the database, it can provide you more properties like SQL error code etc which will help you to get more idea about the situation which has caused the exception
In many place we see code like this.
Here the developer’s intention is just to re-throw the exception. But in most of the situations CLR think that the developer is doing a manual exception throw and it will start building the stack trace from this point, As a result when we see the error page’s stack trace we will not be able to find the exact place or line which caused the actual error, since stack trace will be pointing to the line containing “throw ex” statement.
So better is to avoid this type of coding in future or use just “throw” instead of “throw ex” which will re-throws the exception already available in the context and thus the original stack trace information will be maintained,