1-1 If you are not interested in the contents of an exception object, the catch block parameter may be omitted. T
1-2catch (type p) acts very much like a parameter in a function. Once the exception is caught, you can access the thrown value from this parameter in the body of a catch block. T
2-1One of the major features in C++ is ( ) handling,which is a better way of handling errors. D
A data
B pointer
C test
D exception
2-2What is wrong in the following code? C
vector<int> v;
v[0] = 2.5;
A The program has a compile error because there are no elements in the vector.
B The program has a compile error because you cannot assign a double value to v[0].
C The program has a runtime error because there are no elements in the vector.
D The program has a runtime error because you cannot assign a double value to v[0].
2-3If you enter 1 0, what is the output of the following code? D
#include "iostream"
using namespace std;
int main()
{
// Read two integers
cout << "Enter two integers: ";
int number1, number2;
cin >> number1 >> number2;
try
{
if (number2 == 0)
throw number1;
cout << number1 << " / " << number2 << " is "
<< (number1 / number2) << endl;
cout << "C" << endl;
}
catch (int e)
{
cout << "A" ;
}
cout << "B" << endl;
return 0;
}
A A
B B
C C
D AB
2-4The function what() is defined in __. A
A exception
B runtime_error
C overflow_error
D bad_exception
2-5下列关于异常的描述中,错误的是()。 A
A 编译错属于异常,可以抛出
B 运行错属于异常
C 硬件故障也可当异常抛出
D 只要是编程者认为是异常的都可当异常抛出
2-6下列关于异常类的说法中,错误的是。 A
A 异常类由标准库提供,不可以自定义
B C++的异常处理机制具有为抛出异常前构造的所有局部对象自动调用析构函数的能力
C 若catch块采用异常类对象接收异常信息,则在抛出异常时将通过拷贝构造函数进行对象复制,异常处理完后才将两个异常对象进行析构,释放资源
D 异常类对象抛出后,catch块会用类对象引用接收它以便执行相应的处理动作
7-1 求平方根函数mySqrt的异常处理 (10分)
改造下面的求平方根函数mySqrt,当x小于0时,输出错误信息:“Error: Can not take sqrt of negative number”;当x不小于0时,输出x的平方根。要求在main函数中采用C++的异常处理方法。
double mySqrt(double x)
{ return sqrt(x); }
输入格式:
4
输出格式:
The sqrt of 4 is 2
输入样例:
-9
输出样例:
Error: Can not take sqrt of negative number
#include<iostream>
#include<cmath>
double mySqrt(double x)
{
if (x>=0)
return sqrt(x);
else
return -1;
}
int main()
{
double x,y;
std::cin>>x;
y=mySqrt(x);
if (-1==y)
std::cout<<"Error: Can not take sqrt of negative number";
else
std::cout<<"The sqrt of "<<x<<" is "<<y;
return 0;
}