12

Today I met a weird behaviour in catching exceptions in C++, could anyone clarify it to me? Code snippe

#include <iostream>
#include <string>
#include <exception>


int main() {
  try {
    std::stod("notanumber");
  } catch (const std::invalid_argument&) {
    std::cerr << "std::invalid_argument" << std::endl;
  } catch (const std::out_of_range&) {
    std::cerr << "std::out_of_range" << std::endl;
  } catch (const std::exception&) {
    std::cerr << "Caught by ancestor" << std::endl;
  } catch (...) {
    auto ptr = std::current_exception();
    auto type = __cxxabiv1::__cxa_current_exception_type();
    std::cerr << type->name() << std::endl;
    std::cerr << "..." << std::endl;
  }
  return 0;
}

Writes to output

St16invalid_argument
...

Environment details

C++ 14, disabled RTTI
Clang 13.1.6 arm64-apple-darwin-21.6.0
macOS Monterey 12.6

I expect exception to be caught on the very first catch block

Upd. Even simplest catch doesn't work for me on the environment

try {
  std::stod("notanumber");
} catch (const std::invalid_argument&) { // not caught
  std::cerr << "std::invalid_argument" << std::endl;
}
sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
  • Problem disappears with RTTI turned on, but it's still a question for me – Alexander Gruzintsev Nov 15 '22 at 06:54
  • Without RTTI one cannot downcast with dynamic cast. It's most likely that the exception routines rely on it when catching exceptions. – ALX23z Nov 15 '22 at 06:58
  • Possibly related: https://discourse.llvm.org/t/exception-handling-with-rtti-disabled-on-macos/57479. – Daniel Langr Nov 15 '22 at 07:05
  • @ALX23z The type of a thrown exception in C++ is determined at runtime, and all catch handlers (other than, notionally, maybe the `...` catch-all`) are required to discriminate based on type of the exception. For that reason, I have trouble imagining a scheme in which an implementation could work correctly without RTTI. – Peter Nov 15 '22 at 07:18
  • See https://stackoverflow.com/questions/21737201/problems-throwing-and-catching-exceptions-on-os-x-with-fno-rtti https://stackoverflow.com/questions/3638237/polymorphically-catching-an-exception-in-a-fno-rtti-shared-library-on-mac-os-x – Alan Birtles Nov 15 '22 at 07:24
  • 2
    See update, even simplest catch with invalid_argument doesn't work on mac m1, but works well on intel. Looks like a compiler bug – Alexander Gruzintsev Nov 15 '22 at 08:02
  • 3
    I'm voting to reopen this. The close reason makes no sense at all. This is perfectly reproducible on Mac and there is no typo that causes it. – sebrockm Nov 15 '22 at 13:31
  • With RTTI disabled the compiler is not compiling C++. Check your compiler documentation to see what language features might work in this non-standard environment. – Pete Becker Nov 15 '22 at 14:38

0 Answers0