【问题标题】:where can we use "try catch" and exception? [duplicate]我们在哪里可以使用“try catch”和异常? [复制]
【发布时间】:2018-08-22 14:34:21
【问题描述】:

如何抛出 C++ 异常 C++ 异常处理 我对异常处理的理解很差(即如何为自己的目的自定义 throw、try、catch 语句)。

例如我定义了一个函数如下:int compare(int a, int b){...}

我希望该函数在 a 或 b 为负数时抛出带有某些消息的异常。

我应该如何在函数的定义中处理这个问题?

【问题讨论】:

标签: visual-c++


【解决方案1】:

一点也不。

函数的定义保留

int compare(int a, int b);

无论你是否抛出异常(忘记 throw(exception),它被认为是 bad practice 并且已被弃用)。


如果您想在 a 或 b 为负数时抛出异常,则将此代码放入您的方法中实现

int compare(int a, int b)
{
    if(a < 0 || b < 0)
    {
        throw std::logic_error("a and be must be positive");
    }

    // the comparing code here
}

这就是方法抛出的全部内容。请注意,您需要#include &lt;stdexcept&gt;


对于调用代码(例如main),您可以这样做:

int result;

try
{
    result = compare(42, -10);
}
catch(const std::logic_error& ex)
{
    // Handle the exception here. You can access the exception and it's members by using the 'ex' object.
}

注意我们如何在catch 子句中使用catch the exception as a const reference,以便您可以访问异常成员,例如ex.what(),在这种情况下为您提供异常消息

"a 和 be 必须是正数"


注意。 您当然可以抛出其他异常类型(甚至是您自己的自定义异常),但对于这个示例,我发现std::logic_error 最合适,因为它报告a faulty logic

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-25
    • 1970-01-01
    • 1970-01-01
    • 2011-09-02
    • 2010-10-06
    • 1970-01-01
    相关资源
    最近更新 更多