Time to scribble down some of the things I don’t like seeing when reading C# code.

try {
    something();
}
catch(Exception e){
    //doNothing
}

and

try {
    something();
}
catch(Exception e){
    logSomething();
    //do nothing
}

and

try {
    something();
}
catch(Exception e){
    logSomething();
    return null;
}

and

try {
    something();
}
catch(Exception e){
    //throw base Exception class
    throw new Exception("Something didn't happen");
}

All of these are exception handling anti-patterns and the reason should be obvious. Still I see them all the time. I might even have written some code like this back in the days.

One reason not to write software this way is that your system will have side effects that are impossible to spot. Also, I’m guessing the users of the software won’t like strange things happening in the UI.

To avoid problems like this I’m usually using a combination of custom exceptions and a back stop. When I see the possibility of an exception occuring in my code and it makes sense to create a more specific exception I do just that. Remember to keep the original exception as an inner exception of the new one. To prevent exceptions from bubbling onto the user interface I have a back stop where I catch all exceptions before they are exposed to the user. Since I am throwing custom exceptions in my code I can reason about the exceptions and give the user the proper feedback. Sometimes the exceptions require more attention than just giving feedback to the user. In these cases my exception might become an event that is picket up by the appropriate handler.

I guess this is the common way to handle exceptions, but who knows. Do you have any other strategy ?

Comments F Share