C# Exception Handling Best Practices

Best Practices

Cheatsheet

DO

Control flow with control statements

Keep track of ignored (absorbed) exception by logging

Repeat exception by using throw

Throw predefined system exceptions

Throw custom/predefined exception if it is crucial to application logic

Catch exceptions that you want to handle

DO NOT manage business logic with exceptions.

DON’T

Control flow with exceptions

Ignore exception

Re-throw exception – throw new ArgumentNullException() or throw ex

Throw custom exceptions similar to predefined system exceptions

Throw custom/predefined exceptions to state a warning in flow

Catch every exception

Flow control should NOT be done by exceptions. Use conditional statements instead. If a control can be done with if-else statement clearly, don’t use exceptions because it reduces readability and performance.

READ ALSO
C# Creating a new query using LinqPad

Consider the following snippet by Mr. Bad Practices:

  • This is a snippet example for DO NOT object myObject;
void DoingSomethingWithMyObject()

{

Console.WriteLine(myObject.ToString());

}

When execution reaches Console.WriteLine(myObject.ToString()); application will throw an NullReferenceException. Mr. Bad Practices realized that myObject is null and edited his snippet to catch & handle NullReferenceException:

  • This is a snippet example for DO NOT object myObject;
void DoingSomethingWithMyObject()

{

try




{

Console.WriteLine(myObject.ToString());

}

catch(NullReferenceException ex)

{

Hmmm, if I create a new instance of object and assign it to myObject: myObject = new object();
Nice, now I can continue to work with myObject DoSomethingElseWithMyObject();

}

}

 

Since previous snippet only covers logic of exception, what should I do if myObject is not null at this point? Where should I cover this part of logic? Right after Console.WriteLine(myObject.ToString());? How about after the try…catch block?

READ ALSO
C# If-Else Statement

How about Mr. Best Practices? How would he handle this?

  • This is a snippet example for DO object myObject;
void DoingSomethingWithMyObject()

{

if(myObject == null) myObject = new object();

When execution reaches this point, we are sure that myObject is not null DoSomethingElseWithMyObject();

}

Mr. Best Practices achieved same logic with fewer code and a clear & understandable logic.

DO NOT re-throw Exceptions

Re-throwing exceptions is expensive. It negatively impact performance. For code that routinely fails, you can use design patterns to minimize performance issues. This topic describes two design patterns that are useful when exceptions might significantly impact performance.

DO NOT absorb exceptions with no logging

try

{

//Some code that might throw an exception

}

catch(Exception ex)

{

//empty catch block, bad practice

}

Never swallow exceptions. Ignoring exceptions will save that moment but will create a chaos for maintainability later. When logging exceptions, you should always log the exception instance so that the complete stack trace is logged and not the exception message only.

try

{

//Some code that might throw an exception

}

catch(NullException ex)

{

LogManager.Log(ex.ToString());

}

Do not catch exceptions that you cannot handle

READ ALSO
C# Creating a new project in Visual Studio (console application) and Running it in Debug mode

Many resources, such as this one, strongly urge you to consider why you are catching an exception in the place that you are catching it. You should only catch an exception if you can handle it at that location. If you can do something there to help mitigate the problem, such as trying an alternative algorithm, connecting to a backup database, trying another filename, waiting 30 seconds and trying again, or notifying an administrator, you can catch the error and do that. If there is nothing that you can plausibly and reasonably do, just “let it go” and let the exception be handled at a higher level. If the exception is sufficiently catastrophic and there is no reasonable option other than for the entire program to crash because of the severity of the problem, then let it crash.

try

{

//Try to save the data to the main database.

}

catch(SqlException ex)

{

//Try to save the data to the alternative database.

}

//If anything other than a SqlException is thrown, there is nothing we can do here. Let the exception bubble up to a level where it can be handled.