throw
程序的异常检测用 throw 扔出一个异常。
以一个例子来说明:
/* *func:判断item1和item2是否是同一种书籍 */ Books item1,item2; cin>>item1>>item2; if(item1==item2){ cout<<"yes"<<endl; } else{ cout<<"no"<<endl; }
这是一个普通的函数,下面用异常的方法表示不是同一种书籍。
if(item1!=item2){ throw runtime_error("no"); } cout<<"yes"<<endl;
上面这个代码就表示如果匹配不上时抛出一个runtime_error异常,还有很多异常类可以在c++标准库中查看。
try-catch
![](https://img2020.cnblogs.com/blog/1887631/202009/1887631-20200909161915038-953320588.png)
try-catch语句就是用来编写处理代码的
接着上面那个例子,写出接住异常的代码:
while(cin>>item1>>item2){ try{ //执行比较代码 //如果比较失败,会抛出一个runtime_error异常 }catch(runtime_error){ cout<<error.what()<<endl;//输出异常原因 }
当try中出现异常后就catch中处理。