处理 C++ 中的除以零异常


在本文中,我们将讨论如何在 C++ 中处理除以零异常。

除以零在数学中是一个未定义的实体,所以在编程时我们需要正确地进行处理,以便它在用户端不会返回错误。

使用 runtime_error 类

示例

 在线演示

#include <iostream>
#include <stdexcept>
using namespace std;
//handling divide by zero
float Division(float num, float den){
   if (den == 0) {
      throw runtime_error("Math error: Attempted to divide by Zero\n");
   }
   return (num / den);
}
int main(){
   float numerator, denominator, result;
   numerator = 12.5;
   denominator = 0;
   try {
      result = Division(numerator, denominator);
      cout << "The quotient is " << result << endl;
   }
   catch (runtime_error& e) {
      cout << "Exception occurred" << endl << e.what();
   }
}

输出

Exception occurred
Math error: Attempted to divide by Zero

使用用户定义异常处理

示例

 在线演示

#include <iostream>
#include <stdexcept>
using namespace std;
//user defined class for handling exception
class Exception : public runtime_error {
   public:
   Exception()
   : runtime_error("Math error: Attempted to divide by Zero\n") {
   }
};
float Division(float num, float den){
   if (den == 0)
   throw Exception();
   return (num / den);

}
int main(){
   float numerator, denominator, result;
   numerator = 12.5;
   denominator = 0;
   //trying block calls the Division function
   try {
      result = Division(numerator, denominator);
      cout << "The quotient is " << result << endl;
   }
   catch (Exception& e) {
      cout << "Exception occurred" << endl << e.what();
   }
}

输出

Exception occurred
Math error: Attempted to divide by Zero

使用栈展开

示例

 在线演示

#include <iostream>
#include <stdexcept>
using namespace std;
//defining function to handle exception
float CheckDenominator(float den){
   if (den == 0) {
      throw runtime_error("Math error: Attempted to divide by zero\n");
   }
   else
      return den;
}
float Division(float num, float den){
   return (num / CheckDenominator(den));
}
int main(){
   float numerator, denominator, result;
   numerator = 12.5;
   denominator = 0;
   try {
      result = Division(numerator, denominator);
      cout << "The quotient is " << result << endl;
   }
   catch (runtime_error& e) {
      cout << "Exception occurred" << endl << e.what();
   }
}

输出

Exception occurred
Math error: Attempted to divide by zero

更新于:2020-02-17

8K+ 浏览

开启您的 职业生涯

完成课程获得认证

开始
广告