Even though I\'ve programmed on a professional level for some years I still do n
ID: 642020 • Letter: E
Question
Even though I've programmed on a professional level for some years I still do not fully understand error handling. Although my applications work fine, the error handling isn't implemented at a professional level and is a mix and match of a number of techniques.
There is no structure behind my error handling. I'd like to learn and understand how it's implemented at a professional level. This is one area where I lack knowledge.
When should I use an exceptions and when should I return a success status, to be checked in the logic flow? Is it OK to mix exception and returning a status?
I code in C# mainly.
Explanation / Answer
Use exceptions for exceptional things, the things you can't reasonably expect to encounter too often, things which indicate that something goes wrong. For example, if the network is down, it is an exceptional thing for a web server. If the database is unavailable, it means that something is wrong. If the configuration file is missing, it probably means that the user messed up with it.
Don't use exceptions to handle incorrect code. In order to check the correctness of the code, you should use either the assertions, or, in .NET Framework 4 and later, Code contracts (which replace assertions and have additional, particularly valuable features).
Don't use exceptions in non-exceptional cases. The fact that the user, when asked to enter a number, entered "dog" is not so exceptional to deserve an exception.
Be careful when choosing the types of exceptions. Create your own types when needed. Carefully chose the inheritance, keeping in mind that catching parents will catch the children as well. Never throw Exception.
Don't use return codes for errors. Error codes are easily masked, ignored, forgotten. If there is a error, either handle it, or propagate it to the upper stack.
In cases where a method is expected to return a error and the error is not exceptional, use enums, never error numbers. Example:
// Note that the operation fails pretty often, since it deals with the servers which are
// frequently unavailable, and the ones which send garbage instead of the actual data.
private LoadOperationResult LoadProductsFromWeb()
{
...
}
The meaning of LoadOperationResult.ServerUnavailable, LoadOperationResult.ParsingError, etc. is much more explicit than, say, remembering that code 12 means that the server is down, and code 13
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.