简体   繁体   中英

C++ Exception not caught by base class

I'm compiling the following code with Visual C++ 2017 (C++17 features are enabled)

int main() {
  try {
    // loot is some library that is linked as a dll
    auto game = loot::CreateGameHandle(loot::GameType::fonv, "c:\\something\\invalid", "C:\\something\\invalid");
    // throw std::invalid_argument("this works as expected");
  }
  catch (const std::exception &e) {
    std::cout << "caught as exception " << e.what() << std::endl;
  }
  catch (const std::invalid_argument &e) {
    std::cout << "caught as invalid_argument " << e.what() << std::endl;
  }
  catch (...) {
    std::cout << "caught by ..." << std::endl;
  }
}

The compiler reports, as expected:

warning C4286: 'const std::invalid_argument &': is caught by base class ('const stdext::exception &') on line 8

However, the application output is

caught as invalid_argument Given game path "c:\something\invalid" does not resolve to a valid directory.

And it's not just changing the catch order or something, if I remove the last 2 catch blocks, the application crashes because of the unhandled exception.

How is that even possible? I'm assuming this is somehow related to compiler settings that make my std::exception be a different type from the one std::invalid_argument inside the library inherits from - but why then is my std::invalid_argument the same type as theirs? Is there a way to fix this? Because that library throws a lot of different exception types and I can't really catch each one individually.

Bloody hell, sorry for this. It turns out the build system I was using added _HAS_EXCEPTIONS=0 to the preprocessor definitions. That's what's causing this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM