Error handling, part 2

Error handling, part 2

Sergey Abbakumov

C++

In C++ there's an opportunity to throw the error through all the call stack to the needed handler. By the way, in C there's also such an opportunity using longjmp, however it can not perform stack unwinding with the destructor calls of the local objects:

double Sqrt(double val) {
  if (val < 0.0)
    throw std::invalid_argument("val is less than 0");
  return sqrt(val);
}

try {
  Foo();
} catch (const std::invalid_argument& e) {
  // Error handling.
}

void Foo() {
  Bar();
}

void Bar() {
  const double result = Sqrt(10.0);
}



This approach saves programmers from the routine check the call of every function or method, allows separating error handling from the main code (especially useful in deeply nested functions). One can not ignore the error implicitly. The code becomes cleaner... But...


It's to be understood that this mechanism has its own overhead. On x86 architecture before every function call the compiler generates a special prologue and after the call generates a special epilogue. The exception handling context is created and destroyed in there accordingly. It's not absolutely expensive operation but if the function is small the relative overhead grows.

On x64 architecture there's no performance penalty on the function call. They are called as quickly as if there's no exceptions at all (free try). The information needed to find an exception handler and to call the destructors of the local objects is stored in executable file quite compactly. However when the exception is thrown, the runtime should spend some time for all the needed work.


Also one should remember that exceptions add to the program hidden paths of execution which can be a lot. It's described in Herb's Sutter "Exceptional C++" book. Besides this, you should write exception-safe code in case of resource release even if an exception being thrown (this can be achieved using RAII idiom). This is best described by Jon Kalb: Exception-Safe Coding in C++.

To be continued...


Telegram channel: https://t.me/sea_plus_plus

Report Page