抛出异常并忽略"reaches end of non-void function"警告不好吗?

Is it bad to throw an exception and ignore "reaches end of non-void function" warnings?

本文关键字:function 警告 non-void of reaches end 抛出异常      更新时间:2023-10-16

我的代码:

QSerialPortInfo getCentralInfo()
{
    const QList<QSerialPortInfo> infoList =
            QSerialPortInfo::availablePorts();
    for (auto it = infoList.cbegin();
         it != infoList.cend(); ++it) {
        if (it->manufacturer() == "1a86") {
            happyTalk("Znaleziono centralkę.");
            return *it;
        }
    }
    escape("Nie znaleziono centralki.");
}
void escape(QString errorMsg) {
    qDebug() << "[!] " << errorMsg;
    throw;
}
void happyTalk(QString msg) {
    qDebug() << "[u2713] " << msg;
}

这样停止应用程序是否优雅,为什么不优雅?我得到调试器警告,但我认为这里调试器是错误的。: -)

[[noreturn]]属性添加到escape,并实际抛出一个对象

[[noreturn]]告诉编译器,优化器和希望警告生成器escape永远不会返回,所以它应该(在理想的世界中)阻止该错误。

问题是

throw;

并不表示"抛出一些异常"。它表示"重新抛出当前正在处理的异常"。如果你执行throw没有活动异常,我相信它会调用std::terminate来结束程序。

一种更优雅的处理方法是抛出一个异常(可能是std::logic_error)来指示发生了一些不好的事情,并将控制转移到错误处理程序,或者通过调用exitabort来退出程序。

希望这对你有帮助!