B4J Tutorial Unhandled exceptions

Discussion in 'B4J Tutorials' started by Erel, Mar 19, 2017.

Similar threads

B4J Tutorial SQL Tutorial
B4J Code Snippet Log Stack Trace
B4J Tutorial Msgbox / InputList
Other B4J v5.00 BETA is available for download
B4J Tutorial Pagination Container
  1. Erel

    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):
    Code:
    'Return true to allow the default exceptions handler to handle the uncaught exception.
    Sub Application_Error (Error As Exception, StackTrace As StringAs 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:
    Code:
    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 StringAs Boolean
       LogError(StackTrace)
       
    Return False
    End Sub

    Note that Application_Error is only called in Release mode.


    For server applications the recommended implementation is:
    Code:
    Sub Application_Error (Error As Exception, StackTrace As StringAs 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.
     
    jmon, MichalK73, BPak and 3 others like this.
Loading...