A guidance to Exception Handling
Quoting from Zen Of Python
Errors should never pass silently.
Unless explicitly silenced.
Not many understand the power of logging and exception handling. Logging the right exception details will allow you to inspect the state of an application when the error happened without having a debugger attached. So, exceptions should convey as much information as they can to help you assist the debugging but still should not convey much information to the end user.
I have compiled a list of best practices to be followed for exception handling for .NET but is applicable to any language and this is just a Guidance, not a mandate.
- If an exception can be handled, handle it close to the place of occurrence and log the exception after handling it.
- Unhandled exception should be logged closest to the user to get the full stack trace. Avoid logging the same exception at multiple places in the stack to reduce noise in the logs.
- Log an exception if it is leaving the Application Boundary.
- Never hide an exception. Fail fast and Fail loud.
- Add more data regarding the state of the Application (like inputs, intermediate values, webservice endpoints) by creating a new Exception and assign the original exception as inner exception. Take care not to include any sensitive information like user id and password for connection strings.
- Always use throw instead of throw ex
e.gcatch(Exception ex)
{
throw; //Don’t use throw ex;
} - Have a global trap for all exceptions to log and display a friendly message. Do not expose the exception details to the user. If it has to be, encrypt it and then encode it.
- Handle exceptions only when you know what to do. Avoid using empty catch blocks or catch blocks with just throw.
- Have a global unique identifier which will let you trace the log details across various tiers for the given request, so that exceptions can be correlated.
- Exceptions are costly. Always statically check for errors before performing the action & don’t treat errors as exceptions. E.g Input should be of specific format is an error; while unable to commit changes due to network outage is an exception.
- If you are overriding the ToString() method of an exception class, always log the whole exception class along with InnerException & Stack Trace.
Dear Readers, Please feel free to add your views about Exception handling in the comments.
-
rvramesh
-
Sherwin James







