11/26/2008

Some Tips on Exception Handling

1. Exception V.S. Error Code

- The method you choose depends on how often you expect the event to occur
- Use error code mechanism if it’s a routine case
- Use exception if it’s real exceptional case only
- Never use exception for flow control

2. User Defined Exception

- End user defined exception class names with the word “Exception”
- Ensure that metadata of user defined exceptions is available to code that (may remotely) handles it

3. Exception Safety

- A piece of code is said to be exception-safe, if run time exception will not produce ill effects
- Exception-safe code must satisfy some invariant placed on the code even if exception occurred
- For example, vector<>.add() function should keep the internal state valid/consistent (like element counting) if any exception happened

4. Miscellaneous 

- Always order exceptions in catch blocks from the most specific to the least specific. It handles the specific exception before a general one
- The stack trace begins at the statement where the exception is thrown and ends at the catch statement that catches the exception
- Throw InvalidOperationException if property set or method call is not appropriate given the object state
- Throw ArgumentException if invalid parameters are passed to a function
- Handles resource clean up work in final block
- Logging exception information just once in your whole code stack 

Reference

1. .Net Best Practices for Exception Handling
2. .Net Exception Handling Internals
3. Exception Handling Practices for .Net
4. Exception Handling Practices for Java
5. https://en.wikipedia.org/wiki/Exception_safety

No comments: