在本教程中,我们将讨论如何在C ++中处理“被零除”异常。
除以零是数学中未定义的实体,我们需要在编程时正确地进行处理,以免在用户端出错时返回。
#include <iostream> #include <stdexcept> using namespace std; //处理零除 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; //用户定义的用于处理异常的类 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; //尝试块调用除法功能 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; //定义处理异常的功能 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