c++ - Qt平台如何独立捕获异常?

标签 c++ qt exception exception-handling cross-platform

我在我的项目中使用 boost::date_time。当日期无效时,它会引发 std::out_of_range C++ 异常。在 Windows 平台上的 Qt 的 gui 应用程序中,它成为 SEH 异常,因此它不会被 try|catch 范式捕获并且程序死亡。如何独立捕获异常平台?

try{
    std::string ts("9999-99-99 99:99:99.999");
    ptime t(time_from_string(ts))
}
catch(...)
{
    // doesn't work on windows
}

已编辑: 如果有人不明白,我写了另一个例子:

Qt pro 文件:

TEMPLATE = app
DESTDIR  = bin
VERSION  = 1.0.0
CONFIG  += debug_and_release build_all
TARGET = QExceptExample
SOURCES += exceptexample.cpp \
           main.cpp
HEADERS += exceptexample.h

exceptexample.h

#ifndef __EXCEPTEXAMPLE_H__
#define __EXCEPTEXAMPLE_H__

#include <QtGui/QMainWindow>
#include <QtGui/QMessageBox>
#include <QtGui/QPushButton>
#include <stdexcept>

class PushButton;
class QMessageBox;

class ExceptExample : public QMainWindow
{
  Q_OBJECT
  public:
    ExceptExample();
    ~ExceptExample();
  public slots:
    void throwExcept();
  private:
    QPushButton * throwBtn;
};

#endif

exceptexample.cpp

#include "exceptexample.h"

ExceptExample::ExceptExample()
{
  throwBtn = new QPushButton(this);
  connect(throwBtn, SIGNAL(clicked()), this, SLOT(throwExcept()));
}

ExceptExample::~ExceptExample()
{
}

void ExceptExample::throwExcept()
{
  QMessageBox::information(this, "info", "We are in throwExcept()", 
                           QMessageBox::Ok);
  try{
    throw std::out_of_range("ExceptExample");
  }
  catch(...){
    QMessageBox::information(this, "hidden", "Windows users can't see "
                             "this message", QMessageBox::Ok);
  }
}

main.cpp

#include "exceptexample.h"
#include <QApplication>

int main(int argc, char* argv[])
{
  QApplication app(argc, argv);
  ExceptExample e;
  e.show();
  return app.exec();
}

最佳答案

从评论中添加答案:

aschelper写道:

Is your Qt library compiled with C++ exception support enabled? Sometimes they're not, which causes problems.

hoxnox (OP) 回答:

@aschelper I reconfigured Qt with -exceptions option. It fixed situation. If you'll post the answer I'll mark it as right.

关于c++ - Qt平台如何独立捕获异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4449095/

相关文章:

c++ - 字符串流是如何工作的?

c++ - 恒定大小的 vector

c++ - 在这种情况下如何解耦

python - 在 PDB 交互式 shell 中打印当前异常

java - java中没有但c++具有这些功能的OOP功能是什么?

c++ - 从接口(interface)转换为 QObject

c++ - 为什么我的线程不能正常退出?

java - JDBC 将警告视为数据截断错误

exception - 为什么空的 catch block 是一个坏主意?

c++ - 如何获取脚本以在 C++ 中插入整个用户输入