在C ++中处理被零除的异常
在本教程中,我们将讨论如何在C++中处理“被零除”异常。
除以零是数学中未定义的实体,我们需要在编程时正确地进行处理,以免在用户端出错时返回。
使用runtime_error类
示例
#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
热门推荐
1 狗狗技能训练
5 如何训练狗狗笑
6 狗狗训练排便
9 狗狗响片训练
10 如何训练狗狗不捡食
11 狗狗尿训练
12 怎么训练狗狗找东西
13 狗狗训练站立
14 狗狗训练飞盘
15 鞍山狗狗训练
16 怎样训练泰迪狗狗谢谢
17 狗狗外出训练
18 怎么训练金毛狗狗大小便