34 c++ error-handling qt
我一直在做很多关于使用Qt/C++处理错误的研究,我仍然像我开始时一样迷失.也许我正在寻找一种简单的方法(像其他语言一样).其中一个特别提供了一个我处理过的未处理的例外情况.当程序遇到问题时,它会抛出未处理的异常,以便我可以创建自己的错误报告.该报告从我的客户机器发送到在线服务器,我稍后会阅读.
我在C++中遇到的问题是,任何错误处理都必须考虑到BEFORE手(想想try/catch或大规模条件).根据我的经验,代码中的问题没有被考虑过,否则就不会有问题.
在没有跨平台错误处理/报告/跟踪机制的情况下编写跨平台应用程序对我来说有点吓人.
我的问题是:是否有任何类型的Qt或C++特定的"全能"错误捕获机制,我可以在我的应用程序中使用,以便,如果出现问题,我至少可以在崩溃前写一个报告?
例:
class MainWindow: public QMainWindow
{
[...]
public slots:
void add_clicked();
}
void MainWindow::add_clicked()
{
QFileDialog dlg(this, Qt::Sheet);
QString filename = dlg.getOpenFileName(this);
if(!filename.isEmpty())
{
QStringList path = filename.split(QDir::separator());
QString file = path.at(path.count()); // Index out of range assertion.
if(!lst_tables->openDatabase(filename))
{
[...]
}
}
}
Run Code Online (Sandbox Code Playgroud)
我希望此错误被捕获为未处理的异常和应用程序退出而不向用户显示Windows/Mac操作系统上的默认崩溃窗口.在将断言消息写入文件等之后,我只是希望它能够很好地退出.
Mac*_*cke 33
覆盖QCoreApplication :: notify()并在那里添加try-catch.那个,以及main()中的内容涵盖了我的经验中的大多数情况.
这就是我如何做到的.请注意,我在这里使用的是C++ RTTI,而不是Qt的版本,但这只是为了方便我们的应用程序.此外,我们提供了一个QMessageBox,其中包含info和指向我们日志文件的链接.您应该根据自己的需要进行扩展.
bool QMyApplication::notify(QObject* receiver, QEvent* even)
{
try {
return QApplication::notify(receiver, event);
} catch (std::exception &e) {
qFatal("Error %s sending event %s to object %s (%s)",
e.what(), typeid(*event).name(), qPrintable(receiver->objectName()),
typeid(*receiver).name());
} catch (...) {
qFatal("Error <unknown> sending event %s to object %s (%s)",
typeid(*event).name(), qPrintable(receiver->objectName()),
typeid(*receiver).name());
}
// qFatal aborts, so this isn't really necessary
// but you might continue if you use a different logging lib
return false;
}
Run Code Online (Sandbox Code Playgroud)
此外,我们使用Windows上的__try,__ except来捕获异步异常(访问冲突).谷歌Breakpad可能可以作为跨平台的替代品.
Edw*_*nge 10
你可以在main()中或周围放一个catch(...)这里是:
int main() try
{
...
}
catch (std::exception & e)
{
// do something with what...
}
catch (...)
{
// someone threw something undecypherable
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
55158 次 |
| 最近记录: |