B4J Tutorial Unhandled exceptions

Erel

Administrator
Staff member
Licensed User
Unhandled exceptions are exceptions that were thrown outside of Try / Catch blocks. Such exceptions cause the process to exit in all cases except of server applications.

Starting from B4J v5.0 it is possible to catch such exceptions. This is done with the Application_Error sub (in the Main module):
B4X:
'Return true to allow the default exceptions handler to handle the uncaught exception.
Sub Application_Error (Error As Exception, StackTrace As String) As Boolean
   Return True
End Sub
Returning True from this sub means that the default behavior will be applied so the process will be killed.

Returning False means that the exception is handled. Example:
B4X:
Sub Process_Globals
   Private fx As JFX
   Private MainForm As Form
End Sub

Sub AppStart (Form1 As Form, Args() As String)
   MainForm = Form1
   MainForm.Show
End Sub

Sub MainForm_MouseClicked (EventData As MouseEvent)
   Dim i As Int = "no number here..." 'this will raise an exception.
End Sub

Sub Application_Error (Error As Exception, StackTrace As String) As Boolean
   LogError(StackTrace)
   Return False
End Sub

Note that Application_Error is only called in Release mode.


For server applications the recommended implementation is:
B4X:
Sub Application_Error (Error As Exception, StackTrace As String) As Boolean
   If srvr.CurrentThreadIndex = 0 Then 'main thread
     LogError(StackTrace)
     Return False
   Else 'handlers threads
     Return True
   End If
End Sub
With this code errors raised from the main thread are printed and handled while servlet and WebSocket handlers errors are passed and are caught inside the server library.
Without this code, unhandled main thread exceptions cause the main thread to exit which can eventually break the server.
 
Top