【C++】第五章:异常处理

第五章:异常处理

  • 5.1 异常处理机制
  • 5.2 举个栗子
  • 5.3标准异常

5.1 异常处理机制

  • throw表达式 ,异常检测部分使用throw表达式来表示它遇到了无法处理的问题。我们就说throw引发了异常
  • try语句块,异常处理部分使用try语句处理异常。try语句块以关键字try开始,并以一个或多个catch子句结束。try语句块中代码抛出的异常通常会被某个catch子句处理。因为catch子句“处理”异常,所以它们也称作异常处理代码
  • 一套异常类,用于在throw表达式和相关的catch子句之间传递异常的具体信息

5.2 举个栗子

#include
#include
using namespace std;

int main()
{
     
    string temp1,temp2;
    cout<<"------"<<endl;
    while(cin>>temp1>>temp2)
    {
     
        try{
     
            if(temp1 == temp2)
            {
     
                cout<<"匹配"<<endl;
                break;
            }
            else
            {
     
                throw runtime_error("Data must refer to same ISBN !");  //异常检测
            }
            
        }catch(runtime_error err){
                                //异常处理
            cout<<err.what()<<"\nTry y or n?"<<endl;
            char str;
            cin>>str;
            if( str == 'n')
            {
     
                break;
            }
        }
    }
    cout<<"结束over"<<endl;
}

5.3标准异常

  • 这块还不知道咋用
  • 来一个学一个吧!

你可能感兴趣的:(C++,C++,异常处理)