c++ - 捕获异常 : divide by zero

标签 c++ exception

当我尝试除以 0 时,以下代码没有捕获异常。我需要抛出异常,还是计算机会在运行时自动抛出异常?

int i = 0;

cin >> i;  // what if someone enters zero?

try {
    i = 5/i;
}
catch (std::logic_error e) {

    cerr << e.what();
}

最佳答案

需要自己检查,抛出异常。整数除以零在标准 C++ 中也不异常(exception)。

float 除以零但至少有特定的处理方法。

ISO 标准中列出的异常(exception)情况是:

namespace std {
    class logic_error;
        class domain_error;
        class invalid_argument;
        class length_error;
        class out_of_range;
    class runtime_error;
        class range_error;
        class overflow_error;
        class underflow_error;
}

并且您可以非常有说服力地争论 overflow_error(IEEE754 float 生成的无穷大可以被认为是溢出)或 domain_error(它 输入值有问题)非常适合指示除以零。

但是,5.6 部分(属于 C++11,尽管我认为这与之前的迭代相比没有变化)明确指出:

If the second operand of / or % is zero, the behavior is undefined.

因此,它可以抛出那些(或任何其他)异常。它还可以格式化你的硬盘并 mock :-)


如果你想实现这样的野兽,你可以在下面的程序中使用类似 intDivEx 的东西(使用溢出变体):

#include <iostream>
#include <stdexcept>

// Integer division/remainder, catching divide by zero.

inline int intDivEx (int numerator, int denominator) {
    if (denominator == 0)
        throw std::overflow_error("Divide by zero exception");
    return numerator / denominator;
}

inline int intModEx (int numerator, int denominator) {
    if (denominator == 0)
        throw std::overflow_error("Divide by zero exception");
    return numerator % denominator;
}

int main (void) {
    int i = 42;

    try { i = intDivEx (10, 0); }
    catch (std::overflow_error &e) {
        std::cout << e.what() << " -> ";
    }
    std::cout << i << std::endl;

    try { i = intDivEx (10, 2); }
    catch (std::overflow_error &e) {
        std::cout << e.what() << " -> ";
    }
    std::cout << i << std::endl;

    return 0;
}

这个输出:

Divide by zero exception -> 42
5

您可以看到它抛出并捕获除以零情况下的异常(保持返回变量不变)。


% 等价物几乎完全相同:

关于c++ - 捕获异常 : divide by zero,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42643399/

相关文章:

c++ - 为什么需要强制转换为 bool 值?

c++ - 使用类模板需要模板参数列表?

c++ - Qt C++ 中不同类的信号/插槽功能

c++ - 是否需要使用 MySql Connector/C++ 才能访问/更改 mysql 数据库?

c++ - GStreamer-关键 ** : gst_mini_object_unref: assertion `GST_IS_MINI_OBJECT (mini_object)' failed

Java Post 连接使用 Try 和资源

WCF 服务 SecurityNegotiationException

c# - 全局异常捕获仅在调试 WinForms 应用程序时有效

c# - 我应该处理/捕获这些异常吗?

c# - 如何管理 catch block c# 中的异常?