C++ bool函数的错误处理方法

   2024-09-30 8460
核心提示:在C++中,bool函数通常用于返回一个操作是否成功的布尔值使用异常处理:#includeiostream#include stdexceptbool divide(int a,

在C++中,bool函数通常用于返回一个操作是否成功的布尔值

使用异常处理:
#include<iostream>#include <stdexcept>bool divide(int a, int b, int &result) {    if (b == 0) {        throw std::runtime_error("Division by zero");    }    result = a / b;    return true;}int main() {    try {        int result;        divide(10, 0, result);        std::cout << "Result: "<< result<< std::endl;    } catch (const std::runtime_error &e) {        std::cerr << "Error: " << e.what()<< std::endl;    }    return 0;}
使用错误码:
#include<iostream>enum ErrorCode {    SUCCESS,    DIVISION_BY_ZERO};ErrorCode divide(int a, int b, int &result) {    if (b == 0) {        return DIVISION_BY_ZERO;    }    result = a / b;    return SUCCESS;}int main() {    int result;    ErrorCode error = divide(10, 0, result);    if (error == SUCCESS) {        std::cout << "Result: "<< result<< std::endl;    } else if (error == DIVISION_BY_ZERO) {        std::cerr << "Error: Division by zero"<< std::endl;    }    return 0;}
使用std::optional或std::pair:
#include<iostream>#include<optional>std::optional<int> divide(int a, int b) {    if (b == 0) {        return std::nullopt;    }    return a / b;}int main() {    auto result = divide(10, 0);    if (result) {        std::cout << "Result: " << *result<< std::endl;    } else {        std::cerr << "Error: Division by zero"<< std::endl;    }    return 0;}

这些方法都可以有效地处理bool函数中的错误。选择哪种方法取决于你的需求和编程风格。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号