关于try...catch的三个题目
注:1.如果我们在执行try块内的代码或在try块内的代码调用任何函数期间,没有引起异常,那么程序将继续执行整个try...catch后面的语句;
2.如果我们在执行try块内的代码或在try块内的代码调用任何函数期间,有异常被抛出并被catch捕获处理完成后,其余的catch语句不会再执行,也不会回到抛出异常的位置执行,程序将继续执行try...catch后面的语句;
例一、阅读程序,写出输出结果
#include <iostream>
using namespace std;
class MyException
{
public :
MyException(string msg) { err_msg = msg; }
void ShowErrorMsg() { cout<<err_msg<<endl; }
~MyException() { }
private:
string err_msg;
};
void KindsOfException(int type) throw (MyException,int)//throw()括号里面是throw可能抛掷的所有异常类型
{
switch(type)
{ //只有当参数是0或1的时候才抛出异常
case 0:
throw MyException("Exception! Type of Class");
break;
case 1:
throw 2019;
break;
default: //其它时候不抛出异常,try是检查异常的,没有异常自然不执行try...catch了
break;
}
}
int main( )
{
int type[3] = {1, 2, 0};
for ( int i = 0; i < 3; i++ )
{
try
{
KindsOfException(type[i]);
}
catch(MyException myE)
{
myE.ShowErrorMsg();
continue;
//for循环中执行continue会先跳到上面的i++,再执行i<3的判断条件...
}
catch(int i)
{
cout<<"Exception! Type of Int -->"<<i<<endl;
continue;
}
cout<<"No Exception"<<endl;
}
return 0;
}
输出结果:
例二、阅读程序,写出输出结果
#include <iostream>
using namespace std;
int divide(int x, int y) {
if (y == 0)
throw x;
return x / y;
}
int main() {
try {
cout << "8/3 = " << divide(8, 3) << endl;
cout << "6/0 = " << divide(6, 0) << endl;
cout << "9/2 = " << divide(9, 2) << endl;
} catch (int e) {
cout << e << " is divided by zero!" << endl;
}
cout << "That is ok." << endl;
}
输出结果:
两种,应该是版本不同,都对
第一种:
第二种:
例三、阅读程序,写出输出结果
#include <iostream>
#include <cmath>
#include <stdexcept>
using namespace std;
double area(double a, double b, double c) {
if (a <= 0 || b <= 0 || c <= 0)
throw invalid_argument("the side length should be positive");
if (a + b <= c || b + c <= a || c + a <= b)
throw invalid_argument("the side length should fit the triangle inequality");
double s = (a + b + c) / 2;
return sqrt(s * (s - a) * (s - b) * (s - c));
}
int main() {
double a, b, c;
cin >> a >> b >> c; //输入1 2 4
try {
double s = area(a, b, c);
cout << "Area: " << s << endl;
} catch (exception &e) {
cout << "Error: " << e.what() << endl;
}
}
输出结果:
以上内容供自己期末复习使用,如果有错误,还请大家多多指教~