Trong hướng dẫn này, chúng ta sẽ thảo luận về cách xử lý phép chia cho ngoại lệ Zero trong C ++.
Phép chia cho 0 là một thực thể không xác định trong toán học và chúng tôi cần xử lý nó đúng cách trong khi lập trình để nó không trả về lỗi ở phía người dùng.
Sử dụng lớp runtime_error
Ví dụ
#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();
}
} Đầu ra
Exception occurred Math error: Attempted to divide by Zero
Sử dụng xử lý ngoại lệ do người dùng xác định
Ví dụ
#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();
}
} Đầu ra
Exception occurred Math error: Attempted to divide by Zero
Sử dụng giải nén ngăn xếp
Ví dụ
#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();
}
} Đầu ra
Exception occurred Math error: Attempted to divide by zero