Error Handling – When and Where
At the root of error handling is the need to identify the severity of the problem. If the problem is significant, then it is important to notify someone when the error occurred. These requirements determine the technique necessary to handle an error.
When an error occurs in an application process initiated by an end user, errors are best handled in a friendly fashion. This means you are not going to return a stack trace and details of the error to the users screen. In this case, it is more important to provide the user with actions they need to take as a result of the error.
In those situations, you may also wish to log the error and/or forward the technical details of the error to someone who may be able to route or resolve the issue.This kind of scenario may result in multiple actions occurring for the same error.
Because of the different degrees of complexity in the error contents, often the detailed error is trapped and logged/forwarded as appropriate. Then a more user friendly error message is thrown and returned to the end user.
In the case of automated processes that are not user facing you may still have multiple layers of logging/forwarding depending on the system.
Beware of trapping and re-throwing errors. This can lead to a lot of confusion and make the code difficult to manage. Start at the highest level of code when handling errors. If it becomes necessary to trap errors at a lower layer, say for the purpose of releasing handles on objects, or because data is only available inside of a module that provides information relevant to detailed logging, be sure to re-throw the error allowing it to be funneled up to the higher layer.
One of the most difficult programs I ever worked with was written by a developer who used try/catch in every method. Most times the catch simply threw the error again without performing any action on the error or adding details about the system state at the time of the error. This kind of code provides no benefit and results in higher overhead.
Tomorrow we’ll finish up the discussion on errors with a review of the “using” construct in C#.
Why not share your opinion? I certainly don’t have all the answers for error handling. Even if you don’t agree, send your thoughts on error handling to btaylor@sswug.org. We always get more value with input from the experience of all.
Cheers,
Ben
$$SWYNK$$
Featured White Paper(s)
THE SQL SERVER SECURITY THREAT — IT’S CLOSER THAN YOU THINK
Written by: Kevin Beaver Kevin Beaver, CISSP, is an independent information security consultant, author, expert witness an… (read more)
Featured Script
dba3_NorthWind_0070_Materialized_Object_Refresh_Process_Article
View it now! – Part II: Banishing view timeouts by implementing user "materialized views"… (read more)