0

I am trying to catch this exception but am unable to do so :

#include <unordered_map>
#include <iostream>
#include <exception>


int main() {
    std::unordered_map<int, std::string> x;
    auto it = x.end();
    try { *it; }
    catch (const std::exception& exception) {
        std::cout << "BIG FAT ERROR" << std::endl;
    }
}
expl0it3r
  • 325
  • 1
  • 7
  • 3
    Dereferencing `end` iterator exhibits [undefined behavior](https://stackoverflow.com/questions/2397984/undefined-unspecified-and-implementation-defined-behavior). Anything is allowed to happen. – Igor Tandetnik Aug 22 '20 at 19:09
  • 1
    Well, it [is](https://learn.microsoft.com/en-us/cpp/standard-library/debug-iterator-support) [possible](https://gcc.gnu.org/onlinedocs/libstdc++/manual/debug_mode.html). But the code generation is quite inefficient, not a C++ feature. So they made it "thou shalt not do this". – Hans Passant Aug 22 '20 at 22:34

1 Answers1

2

It is not specified to throw an exception. It is simply Undefined Behaviour. Meaning; if you do that the compiler has no obligations on what code it generates and your entire program is invalid and the compiler also has no obligation to tell you about it.

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70