CPP学习笔记(自用)

2023.10.14

异常捕获

以try,catch,throw三个关键字为组合,try中为可能会出现异常的代码,throw为出现异常后返回的内容,catch为如何处理返回的内容

throw返回字符串

#include <iostream>
#include <cstdlib>

using namespace std;
double hmean(double x, double y);

int main()
{
  double a, b, c;
  cout << "Pls input two number:";
  while (cin >> a >> b)
  {
    try
    {
      c = hmean(a, b);
    }
    catch (const char *s)
    {
      cout << endl
           << s << endl
           << "Enter a new pair of number:" << endl;
      continue;
    }
    cout << "Harmonic mean of " << a << " and " << b << " is " << c << endl
         << "Enter a new pair of number(q to quit):" << endl;
  }
  cout << "Bye!" << endl;

  return 0;
}

double hmean(double x, double y)
{
  if (x == -y)
    throw "bad hmean() arguments:x = -y is not allowed!";
  return 2.0 * x * y / (x + y);
}

throw返回对象

#include <iostream>
#include <cstdlib>
#include <cmath>

using namespace std;

class bad_hmean
{
private:
  double v1;
  double v2;

public:
  bad_hmean(double a = 0, double b = 0) : v1(a), v2(b) {}
  void mesg();
};
inline void bad_hmean::mesg()
{
  cout << "hmean(" << v1 << " , " << v2 << "):invalid arguments:a = -b\n";
}

class bad_gmean
{
public:
  double v1;
  double v2;
  bad_gmean(double a = 0, double b = 0) : v1(a), v2(b) {}
  const char *mesg();
};

inline const char *bad_gmean::mesg()
{
  return "gmean() arguments should be >= 0\n";
}

double hmean(double x, double y);
double gmean(double x, double y);

int main()
{
  double a, b, c;
  cout << "Pls input two number:";
  while (cin >> a >> b)
  {
    try
    {
      c = hmean(a, b);
      cout << "Harmonic mean of " << a << " and " << b << " is " << c << endl
           << "Enter a new pair of number(q to quit):" << endl;
      cout << "Geometric mean of " << a << " and " << b << " is " << gmean(a, b) << endl
           << "Enter a new pair of number(q to quit):" << endl;
    }
    catch (bad_hmean &bg)
    {
      bg.mesg();
      cout << "Try again.\n";
      continue;
    }
    catch (bad_gmean &hg)
    {
      cout << hg.mesg();
      cout << "Value used: " << hg.v1 << " ," << hg.v2 << endl;
      cout << "Sorry, you don't get to play any more.\n";
      break;
    }
  }
  cout << "Bye!" << endl;

  return 0;
}

double hmean(double x, double y)
{
  if (x == -y)
    throw bad_hmean(x, y);
  return 2.0 * x * y / (x + y);
}
double gmean(double x, double y)
{
  if (x < 0 || y < 0)
    throw bad_gmean(x, y);
  return sqrt(x * y);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值