官术网_书友最值得收藏!

Exceptions

So far, we have handled errors in a rather crude way by using the assert macro. Another, more sophisticated, way is to use exceptions. The idea is that when an error occurs, the method throws an exception instead of returning a value. The calling method can choose to handle the exception or to ignore it, in which case it is in turn thrown to its calling method and so on. If no method catches the exception, the execution of the program will finally abort with an error message.

The idea behind exceptions is that the method who discovers the error just throws an exception. It is the calling method that decides what to do with it. The main advantage with exceptions is that we do not have to check for errors after every function call; an exception is thrown at one point in the code and caught at another point. There is a predefined class exception that can be thrown. It is also possible to throw exception of other classes, which may be a subclass of exception, but it does not have to.

Exception.cpp

#include <iostream>
#include <exception>
using namespace std;

double divide(double dNumerator, double dDenominator)
{
  if (dDenominator == 0)
  {
    throw exception("Division by zero.");
  }

  return dNumerator / dDenominator;
}

double invers(double dValue)
{
  return divide(1, dValue);
}

void main()
{
  double dValue;
  cout << ": ";
  cin >> dValue;

  try
  {
    cout << "1 / " << dValue << " = " << invers(dValue)
         << endl;
  }

  catch (exception exp)
  {
    cout << exp.what() << endl;
  }
}
主站蜘蛛池模板: 绥中县| 广丰县| 南涧| 太谷县| 巴东县| 云南省| 吉木萨尔县| 滨州市| 沂源县| 盐亭县| 蓝山县| 驻马店市| 西昌市| 冕宁县| 无为县| 莱阳市| 靖江市| 崇义县| 仲巴县| 白河县| 栾川县| 育儿| 夏邑县| 东丰县| 绵阳市| 靖州| 利津县| 綦江县| 乡宁县| 凤山市| 承德县| 菏泽市| 扎囊县| 名山县| 互助| 鄄城县| 临武县| 华亭县| 承德县| 乌拉特前旗| 定陶县|