Android Question Problem with try/catch: it doesn't catch the crash

Sandman

Expert
Licensed User
Longtime User
I have a problem with try/catch in a sub. The problem is that the code for some mobile phones (Samsung, I'm looking at you!) crash within the try block. I was under the impression that if something crashed in a try-block, all would be good and we'd instead run the code in the catch-block. But here I'm seeing that the app actually crashes.

Have I misunderstood something about try/catch? Or is it simply that I'm doing things "outside" B4X, so to speak, by using JavaObject and running methods there, and the try/catch can't actually catch those crashes?


This the sub:
B4X:
Private Sub getLabelLocationForAllowAllTime As String

    Try
        
        Dim ctxt As JavaObject
        ctxt.InitializeContext
        Dim PackageManager As JavaObject = ctxt.RunMethod("getPackageManager", Null)
          
        Dim res As JavaObject = PackageManager.RunMethod("getResourcesForApplication", Array("com.google.android.permissioncontroller")) ' This line will crash on some phones
              
        Dim resId As Int = res.RunMethod("getIdentifier", Array("app_permission_button_allow_always", "string", "com.android.permissioncontroller"))

        Dim result As String = res.RunMethod("getString", Array(resId))
        
        Return result

    Catch

        Return "fallback string"

    End Try

End Sub
 

Sandman

Expert
Licensed User
Longtime User
Nice idea. I checked, and it's not called. I also realized that I should show the error message in the log:
B4X:
java.lang.ClassCastException: java.lang.StackOverflowError cannot be cast to java.lang.Exception


Do you think there's a reasonable way for me to catch these crashes or should I just give up and remove that sub and always use the fallback string in line 19? It's not the end of the world and I'm not willing to die on this hill - the sub just make the user interface nicer.
 
Upvote 0

agraham

Expert
Licensed User
Longtime User
It looks like a stack overflow error which is unrecoverable so your process will be dumped. A stack overflow is terminal. That error may be Sub Application_Error casting the
StackOverflowError to an Exception and failing. Try changing it to (Error As Object, ...)

B4X:
'Return true to allow the OS default exceptions handler to handle the uncaught exception.
Sub Application_Error (Error As Object, StackTrace As String) As Boolean
    LogColor(Error, Colors.Red)
    Return False
    'Return True
End Sub
If you return False your app will probably die anyway if it has really run out of stack space.
 
Upvote 0

Sandman

Expert
Licensed User
Longtime User
Yep, Error As Object solved the crash. But I don't feel comfortable modifying that sub in Starter. Especially for something as non-important as this. I removed the sub and went with the fallback string. Thanks for helping, much appreciated.
 
Upvote 0
Top