【发布时间】:2023-02-11 23:03:24
【问题描述】:
我开始学习 C++,我尝试创建一个错误来学习如何处理它。 这是我的代码:
#include <iostream>
#include <exception>
int main(){
int res{ 120 }, div{1};
std::cin >> div;
try {
std::cout << res / div << std::endl;
} catch (const std::exception& err) {
std::cout << err.what() << std::endl;
}
std::cout << "Ended" << std::endl;
return 0;
}
程序编译但在执行时,当我输入“0”时,代码停止并且不显示错误。
我使用命令“g++ -std=c++20 -Wall -Wextra -Werror main.cpp -o result”来编译。 我在 VSCode 中使用 Windows 终端或相同的终端,并使用 mingw64 安装了 g++。 我用的是g++ 12.2.0的版本
【问题讨论】:
-
整数除以零导致未定义的行为,不是 C++ 异常。您需要添加明确的代码来保护自己免受它的影响(例如
if (div == 0) { ... }) -
程序崩溃。
echo %ERRORLEVEL%看看吧。