處理 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP