0

my code crashed on map.at(), which means it find a inexisted key.

i catch error in my main, but it seems only can catch the info of

EXCEPTION: _Map_base::at

and no location info, which means i need to check all at function.

Is there any methods can catch this kind of error and print where it crash?

here is my code:

#include <iostream>
using namespace std;

void func() {
  std::unordered_map<int, int> a;
  cout << a.at(2) << endl;
}

void main() {
  try {
    func();
  } catch (const std::exception& ex) { 
    printf("catch EXCEPTION: %s\n", ex.what());  // the mat at error catch here, How can i print the concrete location - func, in the message??????
  }
}
nick
  • 832
  • 3
  • 12
  • 2
    Btw. `void main()` is not valid C++ (by standard). It has to be `int main()` but the `main()` doesn't need to have a `return`. (That's a special rule for `main()` exclusively.) FYI: [SO: What should main() return in C and C++?](https://stackoverflow.com/q/204476/7478597) – Scheff's Cat Jul 20 '21 at 05:00
  • There is no way to retrieve the troublesome call stack in a C++ exception handler, which can get very annoying. A positive side effect is that it makes you more invested in validating data early – when it's much easier to figure out what went wrong – rather than relying on tedious post mortem analysis. This is a good habit in any language. – molbdnilo Jul 20 '21 at 08:04
  • 1
    This is why you use debuggers to debug your code. Any decent debugger will allow you to break where an exception is thrown. – MSalters Jul 20 '21 at 09:00

0 Answers0