微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么“throw”会显示警告?

如何解决为什么“throw”会显示警告?

#include <iostream>
#include <sstream>

using std::string;
using std::cout;
using std::endl;
using std::ostringstream;

class illegalParameterValue {

private:
    string message;
public:
    illegalParameterValue() : message("Illegal parameter value") {}
    explicit illegalParameterValue(const char* theMessage) {message = theMessage;}
    void outputMessage() {cout << message << endl;}

};

int main() {

    ostringstream s;
    s << "index = " << 1 << " size = " << 2;
    throw illegalParameterValue(s.str().c_str());

    return 0;
}

我只是使用了一些这样的代码,但是 throw 会提醒一些调用

的警告

Clang-Tidy:抛出类型“illegalParameterValue”不是从“std::exception”派生的异常

我该如何解决这个问题?

解决方法

考虑以下代码:

try {
  // do something that might throw an exception
}
catch (const std::exception &ex) {
  // handle the exception
}

如果您从 illegalParameterValue 派生 std::exception 类,那么上面的 catch 子句将捕获它(以及从 std::exception 派生的其他类型的异常)。正如目前所写,它不会。您的用户将不得不添加另一个 catch 子句:

try {
  // do something that might throw an exception
}
catch (const std::exception &ex) {
  // handle std exceptions
}
catch (const illegalParameterValue &ip) {
  // handle illegal parameter exeception
}

也许这就是您想要的,也许不是。 但是像第一种情况一样,有很多代码。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。