armanali armanali - 6 days ago 7
C++ Question

Handling exceptions thrown by QPluginLoader::load()

I have 2 Qt plugins, main and helper, with

main.dll
loading
helper.dll
. I am able to successfully load
main.dll
with
QPluginLoader
when both
main.dll
and
helper.dll
are in the same folder. When
helper.dll
is absent and I try to load
main.dll
an exception gets thrown. That's understandable cause
helper.dll
cannot be found. My task is to successfully catch the thrown exception, rather than crashing the app. While debugging here is what Qt Creator displays:

enter image description here

The following code is not solving the problem, so I need to do something else...

std::exception_ptr eptr;
QPluginLoader pluginLoader(packagePath);
try
{
pluginLoader.load();
}
catch(...)
{
eptr = std::current_exception();
}

Answer

I have been able to resolve this. The problem was that my Qt application was not deploying itself (something that a Qt application has to do when it needs to be run independent from Qt creator. I added script to the .pro file of Qt Creator project. Once I did that, I do not see a crash, but a friendly error message generated by calling QPluginLoader::errrorString(), if the call to QPluginLoader::load() returns false.

Here is what my code looks like:

QPluginLoader pluginLoader(m_packagePath);

bool bLoaded = pluginLoader.load();
if (bLoaded)
{
    QObject* plugin = pluginLoader.instance();
    m_metaObject = plugin->metaObject();
    if (m_metaObject == nullptr)
    {
        qCritical() << "Unable to obtain entry class of input plugin. Please check your plugin.";
        return false;
    }
}
else
{
    qCritical() << "Message from Qt plugin loader:";
    qCritical() << pluginLoader.errorString();
    qCritical() << "Please make sure your input Qt plugin along with its dependencies are deployed with winqtdeploy.exe and in the same folder as your plugin.";
    exit(-1);
}

I took the deployment script from another stackoverflow post which can be found here:

Automatic Copy of Dependent Files in Qt Creator

Comments