Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How heavy .NET exception handling is?

Sometimes I have this situation when it's quite easier to wrap whole piece of code in try-catch block rather than do a lot of checking which violently reduce code readability. For example, this

var result = string.Empty;
if (rootObject != null)
{
    if (rootObject.FirstProperty != null)
    {
        if (rootObject.FirstProperty.SecondProperty != null)
        {
            if (!string.IsNullOrEmpty(rootObject.FirstProperty.SecondProperty.InterestingString))
            {
                result = rootObject.FirstProperty.SecondProperty.InterestingString;
            }
        }
    }
}

I really prefer to do like this

var result = string.Empty;
try
{
    result = rootObject.FirstProperty.SecondProperty.InterestingString;
}
catch { }

But after code review I often hear from my mentor that I should avoid try-catch blocks when it's possible to make simple checking. Is it really so critical and each try-catch block eating a lot of system resources (relatively)? Is this resources used only when error raised or each case (successfull or not) is equally "heavy"?

like image 827
Vitalii Korsakov Avatar asked Jan 16 '12 22:01

Vitalii Korsakov


People also ask

What is the best practice for exception handling in C#?

The best practices for Exception Handling in C# are based on logging the exception. The log should be to logging library to keep a record of the exceptions. Log exceptions using log4net, NLog, and other frameworks used for the same purpose.

What are the disadvantages of the exception handling?

Disadvantages. Using exceptions for error handling has two disadvantages. First, exceptions can trap only runtime errors. Therefore, a PL/SQL program cannot trap and recover from compile-time (syntax and semantic) errors such as table or view does not exist.

How are exceptions handled in net?

NET, an exception is an object that inherits from the System. Exception class. An exception is thrown from an area of code where a problem has occurred. The exception is passed up the stack until the application handles it or the program terminates.

Does C# have exception handling?

Exceptions provide a way to transfer control from one part of a program to another. C# exception handling is built upon four keywords: try, catch, finally, and throw.


1 Answers

Whether exceptions are heavyweight or lightweight is completely irrelevant. A thrown exception that could have been easily prevented is a bug. Do not catch the exception: fix the bug so that you don't have to.

like image 188
Eric Lippert Avatar answered Oct 18 '22 20:10

Eric Lippert