[Development] Make Qt6 JNI API safer to use

Bogdan Vatra bogdan.vatra at kdab.com
Thu Mar 5 13:12:39 CET 2020


  I started to review and move androidextras to qtbase (qtbase/src/corelib/
platform/android). Here we have a problem with our Qt JNI API. The problem is 
that in Java exceptions are (ab)used everywhere. Even if we have a way to 
check for exceptions after each call in Qt, it's not used (not even by us in 
Qt code itself), mostly because it's a little unwieldy to use it. To fix this 
issue I'd like to discuss with you a few options:

1 - add something similar to std::expected[0] or outcome[1] to Qt. We can't 
use std::optional because it doesn't work for void function e.g. 
std::optional<void> callMethod(). std::expected allows our API users to 
handle the errors without try/catch. I think std::expected will be useful in 
many places not only for QtJNI e.g. QJsonDocument 
QJsonDocument::fromJson(const QByteArray &json, QJsonParseError *error = 
nullptr) or any other place where we pass the error result as an argument. 
Of course we still need to enable exceptions as if we try to access the 
returned value without checking its state first it will still throw an 
exception if the value is not valid.

2 - use exceptions (at least for android?). This means if a JNI call fails it 
will throw a C++ exception. IMHO this is by far the best, cleanest and easiest 

3 - I'm open for better ideas which makes the coding safer and *easier*.


[0] https://wg21.link/P0323R9 sadly it's not in c++20 :( therefore we need to 
either use an existing implementation or implement one in Qt.
[1] https://ned14.github.io/outcome/ 

More information about the Development mailing list