我正在学习 C++ 中的 try-catch 构造,并且我有以下示例似乎无法执行任一捕获中的代码。在过去的几个小时里,我一直试图在没有运气的情况下找到错误/问题。
我想知道我的机器上的 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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句