5

Possible Duplicate:
How slow are .NET exceptions?

Is there an overhead for throwing an exception and catching it right away? Is there a difference between this

void DoSomething(object basic)
{
    try
    {
       if (basic == null)
         throw new NullReferenceException("Any message");
       else
       {
         //...
       }
    }
    catch (Exception error)
    {
       _logger.WriteLog(error);
    }
}

and this (here we don't throw exception):

void DoSomething(object basic)
{
    try
    {
        if (basic == null)
        {
            _logger.WriteLog(new NullReferenceException("Any message");
            return;
        }
        else
        {
         ...
        }
    }
    catch (Exception error)
    {
        _logger.WriteLog(error);
    }
}

Will the second fragment be faster, or not?

Also I want to know why one solution is faster than another.

Community
  • 1
  • 1
Daniil Grankin
  • 3,841
  • 2
  • 29
  • 39
  • (new NullReferenceException("Any message");) it is my misprint. – Daniil Grankin Sep 10 '12 at 13:58
  • 2
    You can always edit your question to fix it (click the `edit` link) – Sergey Kalinichenko Sep 10 '12 at 14:00
  • If you want to know which is faster, and you already have two valid code snippets, why not just run both (many thousands of times) and find out for yourself? – Servy Sep 10 '12 at 14:01
  • I want to know why? Not only what faster. (Excuse me for my english) – Daniil Grankin Sep 10 '12 at 14:03
  • Thanks, correct questions, take away misprint. – Daniil Grankin Sep 10 '12 at 14:06
  • Edit your question again so that it is clear that you also want to know why one solution is faster than another. – Dialecticus Sep 10 '12 at 14:06
  • @DaniilGrankin The cost of building an exception with a stack trace etc. and throwing it around is obviously higher than a single conditional statement. It's slower simply because the computer has to do more stuff. Also a factor is that people don't spend as much time optimising exception handling because it doesn't need to be fast. – verdesmarald Sep 10 '12 at 14:14

3 Answers3

5

Exceptions are slower than all other program flow but not to the extent they should be avoided for performance reasons. However, they are not meant to be used for program flow. In your situation, you have a very valid alternative that is better than using exceptions. When you can predict a situation and handle it appropriately without exceptions, always do that. Also, don't use exceptions in normal program flow as a convenience.

Use exceptions when you have an unanticipated exceptional situation you can't handle directly.

Samuel Neff
  • 73,278
  • 17
  • 138
  • 182
  • Thanks. First fragment I found in project and I thougth, that better to do without throw exception and ask here. – Daniil Grankin Sep 10 '12 at 14:15
  • What do you think about using try finally for program flow, when in block of try return placed, and in finally block general code, that must execute always, placed? – Daniil Grankin Sep 10 '12 at 14:20
  • @DaniilGrankin, `try`/`finally` is really an important construct to run code, usually cleanup code, regardless of how it's generated (from return, fall-through, or exception). Generally only clean-up code should run in a `finally` and you want to make sure a `finally` absolutely never throws an exception. With those things in mind, always use `try`/`finally` when it's appropriate. – Samuel Neff Sep 11 '12 at 13:04
0

I gather that Throw has a lot more overhead than try/catch does. By that I mean that there is little overhead to having a try/catch, but there is a small overhead once you actually have to catch an exception. In a lot of programs, both of the options you show will be fine, but if you are trying to really profile your code, it will be quicker without the throw. A couple of other questions worth looking at:

Under C# how much of a performance hit is a try, throw and catch block

What is the real overhead of try/catch in C#?

Community
  • 1
  • 1
HaemEternal
  • 2,229
  • 6
  • 31
  • 50
0

In this case I think that the second choice is more faster, but as said @Samuel Neff exceptions are very slow. However, when I was reading a Jon Skeet arcticle about exceptions I found an interesting arcticle by Krzysztof Cwalina: Design Guidelines Update: Exception Throwing., that explains when we should and shouldn't use exceptions. Infact reading it I found an important point says:

1.2 Exceptions and Performance:

One common concern related to exceptions is that if exceptions are used for code that routinely fails, the performance of the implementation will be unacceptable. This is a very valid concern. When a member throws an exception, its performance can be orders of magnitude slower. However, it is possible to achieve good performance while strictly adhering to the exception guidelines that disallow using error codes. Two patterns described in this section suggest ways to do this.

  • Do not use error codes because of concerns that exceptions might affect performance negatively.
Omar
  • 16,329
  • 10
  • 48
  • 66