【问题标题】:C++, why are errors ignored by my windows terminal?C++,为什么我的 Windows 终端会忽略错误?
【发布时间】: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% 看看吧。

标签: c++ windows terminal


【解决方案1】:

在 C++ 中被零除也不例外。 (尽管在操作系统或架构级别上可能有类似名称的东西。)

如果您在 C++ 中进行整数除以零,那么您的程序具有未定义的行为,并且您无法保证它的行为方式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多