//异常的产生
#i nclude <iostream>
#i nclude <string>
using namespace std;
int main()
{
int i=0;
//故意产生异常
cout<<5/i<<endl;
return 0;
//编译通过,执行异常,需要捕获
}
=======
//异常的产生
#i nclude <iostream>
#i nclude <string>
using namespace std;
int main()
{
try
{
int i=0;
//故意产生异常
cout<<5/i<<endl;
}
catch (...) //捕获所有错误
{
cout<<"eror"<<endl;
}
return 0;
//编译通过,执行异常,需要捕获
}
=========
//捕获不符合逻辑的异常或不满足条件的异常
#i nclude <iostream>
#i nclude <string>
using namespace std;
int get_year()
{
int i=1900;
cin>>i;
if(i<1900||i>2007)
{
throw string("error input");
}
return i;
}
int main()
{
int year=0;
try
{
year=get_year();
}
catch (string err)
{
cout<<err<<endl;
return 0;
}
cout<<year<<endl;
return 0;
//编译通过,执行异常,需要捕获
}
=========
//捕获不符合逻辑的异常
#i nclude <iostream>
#i nclude <string>
using namespace std;
void fun()
{
try
{
throw 1;
}
catch(int i)
{
cout<<i<<endl;
//抛出另外一个异常
throw ++i;
}
}
int main()
{
try
{
fun();
}
catch(int i)
{
cout<<i<<endl;
}
return 0;
}
//异常的再抛出,捕捉到异常后,交上层处理,可以再抛异常.
==========