C++——try、throw、catch实例学习程序

#include<iostream>
#include<stdexcept>
//exception/stdexcept/new/type_info头文件里都有定义的标准异常类
using namespace std;
int main()
{
      try{
            int a,b;    char s;
            cin>>a>>s>>b;
            if(s=='/'){
                  if(b==0)  throw "Divided by 0!";
                  cout<<a<<"/"<<b<<"="<<a/b<<endl;
            }
            else
                  if(s=='%') {   
                        if(b==0)      throw a;
                        cout<<a<<"%"<<b<<"="<<a%b<<endl;
                  }
                  else
                        cout<<"Option must be % or /."<<endl;
      }//try
      //捕获int类型的异常并处理
      catch(int i)  {       cout<<"Error occur:"<<i<<"%0"<<endl;  }
      //捕获char* 类型的异常并处理
      catch(char *str) {cout<<"Error occur:"<<str<<endl;  }
      catch(runtime_error err){ cout<<err.what()<<endl;}
      //捕获其他不论什么异常并处理
      catch(...){cout<<"Unkown Error"<<endl;}
      //没错误不执行catch。有错误至多执行一个catch语句块,且不再返回try语句块中。
      //无论有无异常都要执行到此处
      cout<<"Hello world"<<endl;
      return 0;
}

原文地址:https://www.cnblogs.com/yxwkf/p/5257654.html