B4J Question Failed to Try Catch System.load: class java.lang.UnsatisfiedLinkError cannot be cast to class java.lang.Exception

xulihang

Active Member
Licensed User
Longtime User
B4X:
    Try
        Dim System As JavaObject
        System.InitializeStatic("java.lang.System")
        System.RunMethod("load",Array(File.Combine(File.DirApp,"onnxruntime.dll")))
        System.RunMethod("load",Array(File.Combine(File.DirApp,"onnxruntime4j_jni.dll")))
    Catch
        Log(LastException)
    End Try

Using the above code will give the following error:

B4X:
main._appstart (java line: 68)
java.lang.ClassCastException: class java.lang.UnsatisfiedLinkError cannot be cast to class java.lang.Exception (java.lang.UnsatisfiedLinkError and java.lang.Exception are in module java.base of loader 'bootstrap')
    at anywheresoftware.b4a.BA.setLastException(BA.java:399)
    at b4j.example.main._appstart(main.java:68)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at anywheresoftware.b4a.BA.raiseEvent2(BA.java:111)
    at anywheresoftware.b4a.BA.raiseEvent(BA.java:98)
    at b4j.example.main.start(main.java:37)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:846)
 

teddybear

Well-Known Member
Licensed User
UnsatisfiedLinkError is a subclass of java.lang.Error, not a subclass of java.lang.Exception. you can't catch it in b4x.
But you can catch it using inline java.
B4X:
Log(Me.as(JavaObject).RunMethod("load", Array(File.Combine(File.DirApp,"onnxruntime.dll"))))
...
#if java
public static boolean load(String dllpath) {
        try {
            System.load(dllpath);
            return true;
        } catch (UnsatisfiedLinkError e) {
            return false;
        }
}
#End If

 
Upvote 0
Top