为什么这个基本的 Try-Catch 无法捕获

Why does this basic Try-Catch fail to catch

我正在学习 C++ 中的 try-catch 结构,我有以下示例,它似乎无法执行任一捕获中的代码。在过去的几个小时里,我一直在努力寻找 bug/issue,但运气不佳。

我想知道我的机器上的 g++ 是否有问题 -- 我正在使用 mingw 的 g++ 和 Windows 10.

#include <iostream>
#include <stdexcept>

int main(){

    try {
        std::cout << "Start of Try-Catch\n";
        int a = 13;
        int b = 0;
        int p = a/b;
        std::cout << "printing p: " << p << std::endl;
        p = 43;

        std::cout << "Passed the div by zero issue\n";
    } catch (std::runtime_error& e){
        std::cout << "runtime error: " << e.what() << '\n';
        return 2;
    } catch (std::exception& e){
        std::cout << "other error: " << e.what() << '\n'; 
        return 3;
    } catch (...) {
        std::cout << "final catch\n";
        return 4;
    }
    std::cout << "end of program\n";
    return 0;
}

相反,这是我编译时发生的情况 运行:

C:\Users\...\Part 1>g++ cp_bug.cpp -std=c++17

C:\Users\...\Part 1>a.exe
Start of Try-Catch

C:\Users\...\Part 1>

这样做会更合乎逻辑:

int main(){

    try {
        std::cout << "Start of Try-Catch\n";
        int a = 13;
        int b = 0;
        if(b==0)
            throw std::string("Passed the div by zero issue\n");
        int p = a/b;
        
        std::cout << "printing p: " << p << std::endl;
    } catch (std::string e) {
        std::cout << e;
        return -1;
    }
    std::cout << "end of program\n";
    return 0;
}

你的问题是除以零不会抛出可以处理的异常。试试 following tutorial instead.

这个问题也是duplicated