C++ MSVC - 显示未捕获的异常信息

3

我有一个简单的C++代码,想要在Visual Studio 2019中编译:

#include <iostream>
#include <stdexcept>

int main()
{
    std::cout << "Hello World!\n";
    throw std::runtime_error{ "TEST" };
    return 0;
}

PowerShell 中运行此程序,只会显示“Hello world”。根据我使用 GCC 的经验,我期望在终端输出中看到包含 TEST 的消息,例如:
Hello World!                                                                                                                                    
terminate called after throwing an instance of 'std::runtime_error'                                                                             
  what():  TEST                                                                                                                                 
Aborted 

以下是使用的编译器标志:

/permissive- /GS /GL /analyze- /W3 /Gy /Zc:wchar_t /Zi /Gm- /O2 /sdl /Fd"Release\vc142.pdb" /Zc:inline /fp:precise /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_UNICODE" /D "UNICODE" /errorReport:prompt /WX- /Zc:forScope /Gd /Oy- /Oi /MD /std:c++17 /FC /Fa"Release\" /EHsc /nologo /Fo"Release\" /Fp"Release\ThrowTest.pch" /diagnostics:column 

如何在Windows上使用MSVC编译此程序,以显示运行时抛出的异常?

我认为这不是编译或链接的问题,而更多地涉及到在PowerShell中重定向stderr的位置,或者调用您的程序返回的错误代码是什么样的。 - qdbp
请参见 https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/abort?view=vs-2019。 - Alan Birtles
我不知道GCC,但为什么VC会显示 TEST? 你是在寻找调试配置吗? - zdf
3
可能是Visual C++控制台中未显示异常的重复问题。 - user1810087
1个回答

0
如何在Windows上使用MSVC编译此程序,以显示在运行时抛出的异常?如果要在编译后查看消息,则需要try catch块,并且需要捕获异常。
int runTimeError(){
    std::cout << "Hello World!\n";
    try{
        throw std::runtime_error( "TEST" );
    }catch (std::exception& ex){
        std::cout << ex.what();
    }
    return 0;
}

1
要使用MSVC编译,您需要将{}更改为(),或将花括号更改为圆括号。这是不正确的。 - Alan Birtles

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接