Home > Back-end >  C thrown exception message not shown when running app from Windows CMD
C thrown exception message not shown when running app from Windows CMD

Time:08-06

If I run a simple app

#include <stdexcept>

int main() {
    throw std::runtime_error("Hello World!");
}

with Windows CMD, the error message is not shown. How can I fix it?

CodePudding user response:

Let's take a look at what throw does in C from the official Microsoft Docs.

In the C exception mechanism, control moves from the throw statement to the first catch statement that can handle the thrown type.

Note that this means throw does not actually output anything on its own — you'd have to catch it first, then output something. Also note that this means the throw will have to be surrounded by try if you want to do anything with the exception other than terminate the program (which throwing the exception will do on its own).

See below for an example of how to use throw properly.

#include <stdexcept>
#include <cstdio>

int main() {
    try {
        throw std::runtime_error("Hello World!");
    } catch (const std::exception& e) {
        puts(e.what());
    }
}

CodePudding user response:

The only thing guaranteed to happen when an exception escapes main is that the program stops.

To print the message of an exception you have to catch it and print the message

#include <stdexcept>
#include <cstdio>

int main()
{
    try {
        throw std::runtime_exception("Hello World!");
    } catch (const std::exception& e) {
        std::puts(e.what());
    }
}
  • Related