Given the C++ code below, what will be its output?

#include <iostream>
#include <string>
#include <stdexcept>

int main(){
    try{
        throw std::exception("foo");
    } catch(const std::exception& e) {
        std::cout << e.what() << "\n";
    }
}

The answer might surprise you, as it’s compiler dependent, this code will only compile with MSVC compiler!

In this compiler explorer example, we can clearly see that MSVC compiler managed to build the above code, but GCC failed miserably:

<source>: In function 'int main()':
<source>:7:35: error: no matching function for call to 'std::exception::exception(const char [4])'
    7 |         throw std::exception("foo");
      | 

So why is that? Well, it turns out that MSVC includes a std::exception(const char*) constructor, where the standard does not!

To avoid this pitfall and keep the codebase cross platform, one simple approach is just using another derived exception class such as std::runtime_error instead, which has std::runtime_error(const std::string&) constructor built in the standard.

PS

I’m not sure why this discrepancy exist, but there is a Github bug discussing this issue at some more details.