异常被抛出但未被c ++程序

时间:2018-03-06 19:23:55

标签: c++ exception cmd windows-10 try-catch

我正在为大学的练习编写一个c ++程序,他们希望我们抛出一些例外,然后抓住它们并打印一条消息。正如你所看到的,如果任何一个给定的分母为0但是如果你自己运行程序,我会抛出一个Denominator_Is_Zero异常,你可以看到它只是在抛出异常时崩溃,这意味着它没有。完全被抓住了。我在这里缺少什么?

#include "std_lib_facilities.h"

// function forward declarations
void calculateResults(int, int, int, int);
void checkIfDenomIsZero(int , int);

int main() {
  class Denominator_Is_Zero{};
  class Negative_Sqrt_Argument{};

  cout << "Plese insert four integers: \n"; // prompt the user for input
  int numin1,denom1,numin2,denom2; // fraction related variables declaration
  cin >> numin1 >> denom1 >> numin2 >> denom2;
  try {
    checkIfDenomIsZero(denom1,denom2);
    // Otherwise start calculating the desired fraction related values
    calculateResults(numin1,denom1,numin2,denom2);
  } catch(Denominator_Is_Zero &diz) {
    cout << "caught";
    std::cerr << "The denominator cannot be 0!" << '\n';
  } catch(Negative_Sqrt_Argument &nsa) {
    std::cerr << "The square root's argument cannot be negative!" << '\n';
  }
  return 0;
}

// This function checks if either one of the fractions's denominators is 0 and if that's the case, throws an exception
void checkIfDenomIsZero(int denom1,int denom2) {
  class Denominator_Is_Zero{}; // An exception that is thrown when either one of the fractions's denominators is 0
  if(denom1 == 0 || denom2 == 0) {
    throw Denominator_Is_Zero();
  }
}

/**
* This function takes in each fraction's numinator and denominator and
* using the fractions's LCM(Least Common Multiplier) implicitly (ar1 *= par2 and ar2 *= par1), it turns them into homonyms and then
* and then subtracts them. After that, if the subtracted numinator and denominator values
* pass the if() check, it calculates their Square Root and print the desired result to the console.
*/
void calculateResults(int num1,int den1,int num2,int den2) {
  // An exception that is thrown when either the numinator or the denominator of the subtracted fraction is negative (A square root cannot take negative values as arguments)
  class Negative_Sqrt_Argument {};
  num1 *= den2;
  num2 *= den1;
  double resNuminator = num1 - num2;
  double resDenominator = den1*den2;

  // Throw the exception based on the condition described in the exception's comment
  if(resNuminator < 0 || resDenominator < 0) {
    throw Negative_Sqrt_Argument();
  } else { // If the condition is false, then calculate the square root values of the resNuminator and resDenominator
    double sqrtResNum = sqrt(resNuminator);
    double sqrtResDen = sqrt(resDenominator);
    cout << sqrtResNum << "/" << sqrtResDen; // Print the desired result to the console
  }
}

1 个答案:

答案 0 :(得分:1)

您宣布两个不同的Denominator_Is_Zero。一个位于main,一个位于checkIfDenomIsZero

两个Denominator_Is_Zero类不可互换,因为它们分别在两个不同的范围内声明。

您需要声明一个Denominator_Is_Zero类,其中maincheckIfDenomIsZero都可以看到它。在你的程序中,全局定义一个Denominator_Is_Zero类就足够了。