Exception handling unable to understand :(

Hya promotes SO users

First of all, I'm new to C ++, so forgive me if I don't clarify the question. I saw an example of exception handling, but could not understand what is going on here :(

http://codepaste.net/zqsrnj or

enum ErrorCode {โ€ฆ}; // this is exception class ErrorCode dispatcher() { try { throw; // what is thrown here in function?, if rethrow what is rethrown? } catch (std::bad_alloc&) { return ErrorCode_OutOfMemory; } catch (std::logic_error&) { return ErrorCode_LogicError; } catch (myownstdexcderivedclass&) { return ErrorCode_42; } catch(...) { // this will handle the above throw in try block of dispatcher return ErrorCode_UnknownWeWillAllDie; } } ErrorCode apifunc() { try { // foo() might throw anything foo(); } catch(...) { // dispatcher rethrows the exception and does fine-grained handling return dispatcher(); } return ErrorCode_Fine; // } ErrorCode apifunc2() { try { // bar() might throw anything bar(); } catch(...) { return dispatcher(); } return ErrorCode_Fine; } 

Can someone explain this line by line or what is going on here, how is control going? Any help is greatly appreciated, so many thanks.

+4
source share
2 answers

apifunc() and apifunc2() translate exceptions into error codes using the dispatcher() function.

Basically, the following happens: apifunc() (and similarly apifunc2() ) tries to call the foo() function. If foo() throws an exception, then the catch calls dispatcher() to get the error code corresponding to the exception, and then returns this error code. If foo() does not throw, apifunc() returns an ErrorCode_Fine indicating no error.

dispatcher() works by throwing the last exception thrown, i.e. throws one foo() . dispatcher() then checks which exception was thrown using catch blocks and returns the correct error code. For example, if foo() chose std::bad_alloc , then this catch block will be executed and return ErrorCode_OutOfMemory; .

Why would anyone do this?

Exceptions are not necessarily binary compatible in different compilations (compilers, compiler flags, etc.), so the translation of exceptions from error codes is more portable across module boundaries.

+2
source

When foo() throws an exception during its execution, the exception falls into the apifunc() shell, whose catch clause calls the dispatcher() method. There, the "current" exception is thrown (this is the empty throw operator in the dispatcher() method) and is caught again. Then, various catch clauses (bad_alloc, logic_error, myownstdexcderivedclass ... return an error code that will be returned to the outside world.

The final catch(...) clause ensures that an exception will never be passed to apifunc() callers .

+1
source

All Articles