When I read well written code that checks to make sure all the input is of the correct format and type, and also catches all the things that possibly could go wrong, I find it difficult to understand the core of what the program is doing. It seems protection against the non-normal case obscures the normal case.

This includes beginning and ending of array special cases, try-catch, using, handling null, 0, "", and all the other strange things.

How can I write code that is clear, but isn't cluttered by non-normal events??

To make this a little more concrete, how can I do this in C#?

  • You could just do what too many programmers do and ignore the potential errors.....
    – mattnz
    Commented Feb 24, 2014 at 7:28
  • 1
    Just try to imagine what the clutter would look like if you don't have exceptions and you have to check the return value of every call that might fail. Commented Feb 24, 2014 at 7:56

1 Answer 1


There's three specific things I do in my code to deal with this problem:

  • Early return/break/continue

    Although a number of people frown on this as being "like a goto", it helps clear up your code a lot. When you have a test that detects an exceptional condition, handle the condition and get out of the method you're in, instead of cluttering your method up with a huge if/else.

  • Break your code into chunks of meaningful normal execution, surrounded by try...catch blocks

    When you have a piece of code that could possibly throw an exception, instead of dealing with the exception immediately, put all the code that could meaningfully be associated with the risky code inside the try...catch block. That way, the block reads as a meaningful chunk of code. In some ways this is the opposite of the first suggestion, but it's dealing with thrown exceptions instead of boolean conditions.

  • Move exception throwing code into a separate method, so that exceptions are dealt with in one method and the risky code is run in another

    This is just an extreme version of the second recommendation. If the normal flow of logic is big enough to justify it, move it into a separate method and call that method from inside a try...catch block. This can also help when you have several layers of error checking, by separating the layers you can make it easier to read the code.

How these suggestions are applied on depends on what the code allows you to do. I'm also writing from the point of view of a Java programmer; I don't know if there are other mechanisms in C# that would help as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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