Qt 通常不使用,也不完全支持异常抛出(如果你相信的话!)
查看这些链接:
Why doesn't Qt use exception handling?
http://doc.qt.io/qt-5/exceptionsafety.html
也就是说,@Crazy Eddie 和@Macke 的答案非常好,但并不总是有效。特别是,我发现你不能从你从 QML 调用的槽函数中使用它们中的任何一个。因此,我为这个问题创建了一个 hacky 解决方法。 *将此与他们的结合使用 - 而不是代替它。
首先,我创建了从 QException 派生的类,我将在此处跳过,但您可能会想要这样做。在这篇文章中,我只是将其称为“MyQException”。
不管怎样,为一个名为QmlSlotThrower的类添加这个标题:
#ifndef QMLSLOTTHROWER_H
#define QMLSLOTTHROWER_H
#include "MyQException.h"
class QmlSlotThrower
{
public:
static QmlSlotThrower *get()
{
static QmlSlotThrower instance;
return &instance;
}
QmlSlotThrower( QmlSlotThrower const& ) = delete;
void operator=( QmlSlotThrower const& ) = delete;
void throwToTop( const MyQException &exception );
private:
QmlSlotThrower(){}
};
static QmlSlotThrower *qmlSlotThrower = QmlSlotThrower::get();
#define throwFromQmlSlot( exc ) qmlSlotThrower->throwToTop( exc ); return;
#endif // QMLSLOTTHROWER_H
那么,就是cpp:
#include "QmlSlotThrower.h"
#include <QTimer>
class AsynchronousThrower: public QObject
{
Q_OBJECT
public:
void throwThis( const MyQException &exception )
{
exception_ = exception;
QTimer::singleShot( 0, this, SLOT( throwIt() ) );
}
private slots:
void throwIt(){ throw exception_; }
private:
MyQException exception_;
};
static AsynchronousThrower asycnThrower;
// This is needed to allow the Q_OBJECT macro
// to work in the private classes
#include "QmlSlotThrower.moc"
// --------------------------------
void QmlSlotThrower::throwToTop( const MyQException &exception )
{ asycnThrower.throwThis( exception ); }
最后,这是一个示例实现:
void someQMLSlot()
{
// Qt has been progressively adding exception handling
// support, but you still cannot throw from a QML
// triggered slot. It causes an uncatchable fatal error!
// As a general rule, don't throw in Qt unless you are
// certain something is there to catch it. You cannot
// count on an uncaught exception handler at a top level
// to always work. This QML problem is a perfect example.
// So this is not an option here!
//throw MyQException( "Something terrible occured!" );
// This work around, however, can be used instead!
//throwFromQmlSlot( MyQException( "Something terrible occured!" ) )
// Or, to be more robust in illustrating how you can still use
// normal throws from nested functions even, you can do this:
try{ throw MyQException( "Something terrible occured!" ); }
catch( const MyQException &e) { throwFromQmlSlot( e ) }
qDebug() << "YOU SHOULD NEVER SEE THIS!!";
}
只能直接从您的插槽中使用宏!