C++异常处理

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;
}
  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wings(hha)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值