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.

  • 2
    Why down vote? I am asking a serious question about error handling implementation and how it's done. If this isn't the best place to ask such a question among programmers then where is? It really bugs me when people down vote such questions because there is nowhere else to ask such a question. It's possibly the only place on the web where I am going to get a reliable answer and possible resources. So instead of down voting a question that other people will surely Google wouldn't it be easier to answer it? Sep 9, 2013 at 12:45
  • 6
    Your question is very broad. Perhaps you could narrow the scope by relating specific examples of how you have failed to achieve your coding goals. Sep 9, 2013 at 12:59
  • There are many articles on the web about error handling: Try this: msdn.microsoft.com/en-us/library/seyhszts.aspx Sep 9, 2013 at 13:59

2 Answers 2

  1. 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.

  2. 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).

  3. 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.

  4. 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.

  5. 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.

  6. 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 — that the data cannot be parsed.

  7. Use error codes when they refer to the common ones, known by every developer who works in the specific domain. For example, don't reinvent an enum value for HTTP 404 Not Found or HTTP 500 Internal Server Error.

  8. Beware of booleans. Sooner or later, you will want to know not only whether a specific method succeeded or failed, but why. Exceptions and enums are much more powerful for that.

  9. Don't catch every exception (unless you're at the very top of the stack). If you catch an exception, you should be ready to handle it. Catching everything is showing that you don't care if your code runs correctly. This may solve the "I don't want to search right now how to fix this", but will hurt you sooner or later.

  10. In C#, never rethrow exceptions like this:

    catch (SomeException ex)
        throw ex;

    because you're breaking the stack. Do this instead:

    catch (SomeException)
  11. Make an effort when writing exception messages. How many times I've seen something like throw Exception("wrong data") or throw Exception("shouldn't call this method in this context"). Other developers, including yourself six months later, would have no idea what data is wrong and why or why shouldn't we call some method in a context, nor which context precisely.

  12. Don't show exception messages to the user. They are not expected for ordinary people, and often are even unreadable for developers themselves.

  13. Don't localize exception messages. Searching the documentation for a localized message is exhausting and pointless: every message should be in English and English only.

  14. Don't focus exclusively on exceptions and errors: logs are also extremely important.

  15. In .NET, don't forget to include exceptions in XML documentation of the method:

    /// <exception cref="MyException">Description of the exception</exception>

    Including exceptions in XML documentation makes things much easier for the person who is using the library. There is nothing more annoying than trying to guess which exception could be possibly thrown by a method and why.

    In this sense¹, Java exception handling provides a stricter, better approach. It forces you to either deal with exceptions potentially thrown by the called methods, or declare in your own method that it can throw the exceptions you don't handle, making things particularly transparent.

¹ This being said, I find Java distinction between exceptions and errors pretty useless and confusing, given that the language has checked and unchecked exceptions. Luckily, .NET Framework has only exceptions, and no errors.

  • I learned quote a bit from this, May I ask where the list came from? Site or personal experience? Either way exceptional job (hehe get it?).
    – Shelby115
    Sep 9, 2013 at 15:39
  • @Shelby115: the list comes from, in order: Stack Exchange, personal experience and Code Complete by Steve Mcconnell. Sep 9, 2013 at 15:58
  • Thank you @MainMa that is an excellent response! I used to own Code Complete when I was at University but someone stole it. I didn't get to read it. Sep 9, 2013 at 16:08
  • @JamesJeffery: then borrow the second edition in a library, or buy one: it is one of the rare development-related books which is totally worth the money. Sep 9, 2013 at 18:27
  • @MainMa Just ordered from Amazon, thanks :D I also own Clean Code, and totally forgot about Chapter 7. Sep 9, 2013 at 18:41

I think MainMa's list is very complete. I'll just add a few of my own:

  1. Read Eric Lippert's article on how he categorizes exceptions. Particularly important is his point on not catching exceptions that are in reality bugs in your code. Fix the code instead!
  2. If you know that an exception can occur AND you can do something about it, handle it, but limit the scope of you try-catch and catch the specific exception you're expecting. That is, don't do this:

public void Foo() {
    try {
        //get input from use
        //do calculations
        //open file
    catch (Exception ex) {
       //handle exception

Instead do this:

public void Foo() {
    //get input from use
    //do calculations
    try {
        //open file
    catch (FileOpenException ex) {
       //handle exception
  • Don't use exceptions for control flow. For example, don't throw a ClientNotFoundException in a lookup dialog (a client not found is non exceptional in this situation) and expect the calling code to show a "No results found" message when this happens.

  • Don't swallow exceptions!

  • Keep in mind that truly handling an exception can only mean 3 things:

    1. Retry the operation. Only valid if the problem is transient.
    2. Try an alternative.
    3. Notify someone about the problem. Only valid if the notification is actionable, meaning that the user can do something about it.

    If none of these options apply then you probably shouldn't catch that exception. You should log it, though, and then either cancel the operation or shut down. Of course this depends what your requirements are in regards to correctness vs robustness.

Not the answer you're looking for? Browse other questions tagged or ask your own question.