Why are try blocks expensive?

前端 未结 11 2395
醉酒成梦
醉酒成梦 2020-12-02 13:13

I\'ve heard the advice that you should avoid try catch blocks if possible since they\'re expensive.

My question is specifically about the .NET platform: Why are try

相关标签:
11条回答
  • 2020-12-02 13:39

    It's not the block itself that's expensive, and it's not even catching an exception, per se, that's expensive, it's the runtime unwinding the call stack until it finds a stack frame that can handle the exception. Throwing an exception is pretty light weight, but if the runtime has to walk up six stack frames (i.e. six method calls deep) to find an appropriate exception handler, possibly executing finally blocks as it goes, you may see a noticeable amount of time passed.

    0 讨论(0)
  • 2020-12-02 13:41

    You shouldn't avoid try/catch blocks as that generally means you aren't properly handling exceptions that might occur. Structured Exception Handling (SEH) is only expensive when an exception actually occurs as the runtime must walk the call stack looking for a catch handler, execute that handler (and there may be more than one), then execute the finally blocks, and then return control back to the code at the right location.

    Exceptions are not intended to be used to control program logic, but rather to indicate error conditions.

    One of the biggest misconceptions about exceptions is that they are for “exceptional conditions.” The reality is that they are for communicating error conditions. From a framework design perspective, there is no such thing as an “exceptional condition”. Whether a condition is exceptional or not depends on the context of usage, --- but reusable libraries rarely know how they will be used. For example, OutOfMemoryException might be exceptional for a simple data entry application; it’s not so exceptional for applications doing their own memory management (e.g. SQL server). In other words, one man’s exceptional condition is another man’s chronic condition. [http://blogs.msdn.com/kcwalina/archive/2008/07/17/ExceptionalError.aspx]

    0 讨论(0)
  • 2020-12-02 13:41

    Slightly O/T, but...

    There is fairly good design concept that says you should never require exception handling. This means simply that you should be able to query any object for any conditions that might throw an exception before that exception would be thrown.

    Like being able to say "writable()" before "write()", stuff like that.

    It's a decent idea, and if used, it makes checked exceptions in Java look kind stupid--I mean, checking for a condition and right after that, being forced to still write a try/catch for the same condition?

    It's a pretty good pattern, but checked exceptions can be enforced by the compiler, these checks can't. Also not all libraries are made using this design pattern--it's just something to keep in mind when you are thinking about exceptions.

    0 讨论(0)
  • 2020-12-02 13:50

    I think people really overestimate the performance cost of throwing exceptions. Yes, there's a performance hit, but it's relatively tiny.

    I ran the following test, throwing and catching a million exceptions. It took about 20 seconds on my Intel Core 2 Duo, 2.8 GHz. That's about 50K exceptions a second. If you're throwing even a small fraction of that, you've got some architecture problems.

    Here's my code:

    using System;
    using System.Diagnostics;
    
    namespace Test
    {
        class Program
        {
            static void Main(string[] args)
            {
                Stopwatch sw = Stopwatch.StartNew();
                for (int i = 0; i < 1000000; i++)
                {
                    try
                    {
                        throw new Exception();
                    }
                    catch {}
                }
                Console.WriteLine(sw.ElapsedMilliseconds);
                Console.Read();
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-02 13:52

    I doubt if they are particularly expensive. A lot of times, they are necessary/required.

    Though I strongly recommend using them only when necessary and at the right places / level of nesting instead of rethrowing the exception at every call return.

    I would imagine the main reason for the advice was to say that you shouldnt be using try-catches where if---else would be a better approach.

    0 讨论(0)
提交回复
热议问题