Monday, 15 June 2015

Exception Handling - Best Practices

Exception Handling: A well known Concept. I hope everyone knows about it. A very simple but crucial piece of code.
In C#, it's all about try, catch and finally block.

try
{
//Contains code which could throw unexpected error at run time which is called exception.
}
Catch(Exception)
{
//Contains exception handle logic, Ex.: logging.
}
finally
{
//Contains code which will get executed if try block is executed. It will get executed if there is no exception or even if there is exception. Ex.: used to do memory release, connection close etc.
}

Looks very simple but still programmers do mistakes. So here I am going to discuss few best practices which I learned from my past experience.

1. Throwing exceptions hit performance badly. So try to minimize the 'throw' as much as possible.
Ex.:

the piece of code "throw ex" is bad practice instead you should write just "throw;"

5. Don't catch exception if you are not doing anything with the exception details.6. All your public method must have 'try-catch' block instead of having it in private methods.Note: Handle exception in private methods only if have no intention to throw exception to calling method.

7. Don't keep your catch block dumb.
Ex.

bool Method()
{
bool status;
try
{
//Code
}
Catch{}
return status;
}

In above code you basically eat the exception. In this case if someone is calling this method he will always get returned FALSE and calling method will never know why return status is false.

Exception details always contains crucial and confidential information as it contains detail about the code, logic, resource details etc. So by writing above code you are basically creating a security risk by passing information to calling method.

9. Always use Custom Exception to throw exception when it is raised by service which is going to get consumed by different consumers directly.
Ex. If you are developing a service library or an API which can be consumed by different consumer. In this case you should not throw actual exception as it contains details about you business logic.

10. Don't forget to use try-catch or you will end up showing yellow page with exception details to the user.