您的位置:首页 > 编程语言 > C语言/C++

C++中异常处理

2015-12-30 10:51 465 查看
//异常处理
#include <iostream>

using namespace std;

int Test(int i)
{
if(i == 1)
{
throw 0;
}
else if(i == 2)
{
throw 'a';
}
else if(i == 3)
{
throw "Hello";
}
else if(i == 4)
{
throw 0.5;
}

return i;
}
int main()
{
for(int i=0;i<5;i++)
{
try
{
cout << Test(i) << endl;;
}
//根据返回值类型来判断选择哪个catch语句
catch(int e)
{
//同一数据类型可以使用if来判断
if(e == 0)
{
cout << "Exception : int " << e << endl;
}
else
{
cout << "Exception : int !0" << e << endl;
}

}
catch(char e)
{
cout << "Exception : char " << e << endl;
}
catch(const char* e)
{
cout << "Exception : const char* " << e << endl;
}
catch(double e)
{
cout << "Exception : double " << e << endl;
}
}
return 0;
}


//异常处理
#include <iostream>

using namespace std;

int Test(int i)
{
if(i == 1)
{
throw 0;
}
else if(i == 2)
{
throw 'a';
}
else if(i == 3)
{
throw "Hello";
}
else if(i == 4)
{
throw 0.5;
}

return i;
}
int main()
{
for(int i=0;i<5;i++)
{
try
{
cout << Test(i) << endl;;
}
catch(...)   //捕获任意类型的异常
{
cout << "Exception!"<< endl;
}
}
return 0;
}


//异常处理
#include <iostream>

using namespace std;

int Test(int i)
{
if((6 <= i)&&(i <= 8))
{
throw 0;
}
return i;
}
int main()
{
try
{
for(int i=0;i<10;i++)
{
try
{
cout << Test(i) << endl;;
}
catch(int e)
{
cout << "Exception!" << e << endl;
throw e;    //catch再次抛出异常
}
}
}
catch(int e)
{
cout << "Catch : " << e << endl;
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: