Exception Handling

I heard people say that exception handling is a bit expensive due to a stack break.

I donโ€™t get anything, the expansion of the stack occurs if I throw an exception and if I use โ€œreturnโ€. So where is the difference?

If, for example, I get a memory problem that I cannot handle, the only option is to stop the function until I get to the area where the problem needs to be processed or notified. So what is my other option for throwing exceptions?

I can use "return" instead of throwing exception, but then it is the same. I know that expanding the stack can even go back six stacks, but so checking the return value and "return" in combination.

An explanation would be welcome.

+3
source share
7 answers

When you use return, the stack "unfolds" unconditionally, which can conceptually be as simple as executing a single machine code instruction "ret". In exceptional cases, stack promotion should look for a suitable exception handler, which is a much more complicated task. The exception path also has the task of constructing and probably copying the exception object, which may not be trivial.

+7
source

Stack deployment differs from simple return. It also includes searching for an error handler (catch block) at each lower level in the stack. This makes it a difficult process.

. , ; "" . , , , .

, ( ), , . , ?

void MyMethod()
{
    try
    {
        Method1(); 
        Method2();
        Method3();
    }
    catch(SomeException const & e) // edited per Mordachai suggestion
    {
       // handle SomeException
    }
    catch(SomeOtherException const & e)
    {
       // handle SomeOtherException
    }
}

void MyMethod()
{
    int err;
    err = Method1();
    switch(err)
    {
        case SOMEERRORCODE:
             // handle some error code
             break;
        case SOMEOTHERERRORCODE:
             // handle some other error code
             break;          
    }
    err = Method2();
    switch(err)
    {
        case SOMEERRORCODE:
             // handle some error code
             break;
        case SOMEOTHERERRORCODE:
             // handle some other error code
             break;          
    }
    err = Method3();
    switch(err)
    {
        case SOMEERRORCODE:
             // handle some error code
             break;
        case SOMEOTHERERRORCODE:
             // handle some other error code
             break;          
    }
}
+3

- , ( ).

, , , . , , , , .

+2

"" , . , RTTI. , , , , ++, ; -)

, () , ( , ) () , , , .

, , , .

+1

, ++ ( 5.4).

+1

, , . , .

, , , . , , .

+1

Most versions of exception handling add a little extra overhead to help the compiler deal with issues such as scope. Here is an article that has an explanation. The overhead we are talking about is very small and you should almost never worry.

0
source

Source: https://habr.com/ru/post/1724968/


All Articles