C++:throw 和 try-catch


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

 try-catch语句就是用来编写处理代码的  

接着上面那个例子,写出接住异常的代码:

while(cin>>item1>>item2){
  try{   
    //执行比较代码
    //如果比较失败,会抛出一个runtime_error异常
    }catch(runtime_error){
          cout<<error.what()<<endl;//输出异常原因        
    }  
当try中出现异常后就catch中处理。













最好的开始时间是以前,其次是现在。
原文地址:https://www.cnblogs.com/dragonsbug/p/13639817.html