#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;
}
C++——try、throw、catch实例学习程序
最新推荐文章于 2026-05-31 03:13:52 发布
本文提供了一个C++程序实例,演示了如何使用标准异常类进行错误处理和捕获,包括整型异常、字符串异常及运行时异常的处理。

6368

被折叠的 条评论
为什么被折叠?



