C++学习之路: try&catch 语句块处理异常
#include <iostream> #include <string> #include <vector> #include <stdexcept> using namespace std; //对于不同的异常可以采取不同的catch块进行捕捉 int main(int argc, const char *argv[]) { try { int i; cin >> i; if(i == 0) throw runtime_error("出现运行期错误"); //发送一个runtime_error异常 else if(i == 1) throw invalid_argument("非法参数"); } catch(runtime_error &e) { cout << "runtime_error :" << e.what() << endl; //e.what()中保存着错误信息 } catch(invalid_argument &e) { cout << "invalid_argument:" << e.what() << endl; } cout << "继续运行" << endl; return 0; }
#include <iostream> #include <string> #include <vector> #include <stdexcept> using namespace std; //异常捕获不到,照样因为core dump int main(int argc, const char *argv[]) { try { int i; cin >> i; if(i == 0) throw runtime_error("出现运行期错误"); else if(i == 1) throw invalid_argument("非法参数"); } catch(runtime_error &e) { cout << "runtime_error :" << e.what() << endl; } cout << "继续运行" << endl; return 0; }
如果没有捕捉到异常则跳过CATCH继续执行后面的代码
try & catch是处理异常十分好用的一种语句块。要多加练习
以下是一个重要的模板
#include <iostream> #include <string> #include <vector> #include <stdexcept> using namespace std; //对于不同的异常可以采取不同的catch块进行捕捉 //对于一部分可以统一处理 int main(int argc, const char *argv[]) { try { int i; cin >> i; if(i == 0) throw runtime_error("出现运行期错误"); else if(i == 1) throw invalid_argument("非法参数"); else if(i == 2) throw logic_error("逻辑错误"); else throw out_of_range("越界错误"); } catch(...) //能捕获所有的异常 { } catch(exception &e) { cout << "异常信息:" << e.what() << endl; } catch(runtime_error &e) { cout << "runtime_error :" << e.what() << endl; } catch(invalid_argument &e) { cout << "invalid_argument:" << e.what() << endl; } cout << "继续运行" << endl; return 0; }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步