Cheatsheet

Untitled Database

DO NOT manage business logic with exceptions.

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.

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?

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