[Development] Make Qt6 JNI API safer to use

Vitaly Fanaskov vitaly.fanaskov at qt.io
Thu Mar 5 16:14:44 CET 2020

I think something like std::expected is a nice thing to have.

There is some experimental implementation of std::expected: 

Another good example is Result 
(https://doc.rust-lang.org/std/result/index.html) type from Rust. But 
might look clumsy in C++, because there is neither pattern matching nor 
to handle this case gracefully.

Regarding using exceptions, well, I would vote for this option, but I 
don't think that this is possible at all to convince people to use 
exceptions in this module.

On 3/5/20 1:12 PM, Bogdan Vatra via Development wrote:
> Hi,
>    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
> solution.
> 3 - I'm open for better ideas which makes the coding safer and *easier*.
> Cheers,
> BogDan.
> [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/
> _______________________________________________
> Development mailing list
> Development at qt-project.org
> https://lists.qt-project.org/listinfo/development

Best Regards,

Fanaskov Vitaly
Senior Software Engineer

The Qt Company

More information about the Development mailing list