ScriptForge.Exception service (SF_Exception) /text/sbasic/shared/03/sf_exception.xhp
Exception service

ScriptForge.Exception service

The Exception service is a collection of methods to assist in code debugging in Basic and Python scripts and in error handling in Basic scripts. In Basic scripts, when a run-time error occurs, the methods and properties of the Exception service help identify the error context and allow to handle it.
The SF_Exception service is similar to the VBA Err object. The Number property identifies the error. Use the Raise method to interrupt processing. The RaiseWarning method can be used to trap an anomaly without interrupting the macro execution. Errors and warnings raised with the Exception service are stored in memory and can be retrieved using the Console method. The Exception service console stores events, variable values and information about errors. Use the console when the Basic IDE is not easily accessible, for example in Calc user defined functions (UDF) or during events processing. Use the DebugPrint method to add any relevant information to the console. Console entries can be dumped to a text file or visualized in a dialog window. When an error occurs, an application macro may: Report the error in the Exception console Inform the user about the error using either a standard message or a custom message Optionally stop its execution In Python scripts the Exception service is mostly used for debugging purposes. Methods such as DebugPrint, Console and DebugDisplay are useful to quickly print messages, log data and open the console window from within a Python script. Not all methods and properties are available for Python scripts since the Python language already has a comprehensive exception handling system.

Service invocation

The following examples show three different approaches to call the method Raise. All other methods can be executed in a similar fashion. SF_Exception.Raise(...) Dim exc : exc = SF_Exception exc.Raise(...) Dim exc : exc = CreateScriptService("Exception") exc.Raise(...) The code snippet below creates an instance of the Exception service, logs a message and displays the Console window. from scriptforge import CreateScriptService exc = CreateScriptService("Exception") someVar = 100 exc.DebugPrint("Value of someVar", someVar) exc.Console()

Properties

The properties listed below are only available for Basic scripts. Name Readonly Description Description No The error message text. Default value is "" or a string containing the Basic run-time error message. Number No The code of the error. It can be a numeric value or text. Default value is 0 or the numeric value corresponding to the Basic run-time error code. Source No The location in the code where the error occurred. It can be a numeric value or text. Default value is 0 or the code line number for a standard Basic run-time error.
Raising or clearing an Exception resets its properties. List of Methods in the Exception Service Clear
Console
ConsoleClear
ConsoleToFile
DebugDisplay
DebugPrint

PythonPrint
PythonShell
Raise
RaiseWarning
Clear -------------------------------------------------------------------------------------------------------------------------- Exception service;Clear

Clear

Resets the current error status and clears the SF_Exception properties. SF_Exception.Clear() The following example shows how to catch a division-by-zero exception, whose error code is 11. Sub Example_Clear() Dim a, b, c On Local Error GoTo Catch Try: a = 10 : b = 0 c = a / b '... Exit Sub Catch: If SF_Exception.Number = 11 Then SF_Exception.Clear() 'If division by zero, ignore the error End Sub For a complete list of Basic run-time error codes, refer to Debugging a Basic Program.
Console -------------------------------------------------------------------------------------------------------------------------- Exception service;Console

Console

Displays the console messages in a modal or non-modal dialog. In both modes, all the past messages issued by a DebugPrint() method or resulting from an exception are displayed. In non-modal mode, subsequent entries are added automatically. If the console is already open, when non-modal, it is brought to the front. A modal console can only be closed by the user. A non-modal console can either be closed by the user or upon macro termination. exc.Console(modal: bool = True) modal: Determine if the console window is modal (True) or non-modal (False). Default value is True. SF_Exception.Console(Modal := False) exc.Console(modal = False)
ConsoleClear -------------------------------------------------------------------------------------------------------------------------- Exception service;ConsoleClear

ConsoleClear

Clears the console keeping an optional number of recent messages. If the console is activated in non-modal mode, it is refreshed. exc.ConsoleClear(keep: int = 0) keep: The number of recent messages to be kept. Default value is 0. The following example clears the console keeping the 10 most recent messages. SF_Exception.ConsoleClear(10) exc.ConsoleClear(10)
ConsoleToFile -------------------------------------------------------------------------------------------------------------------------- Exception service;ConsoleToFile

ConsoleToFile

Exports the contents of the console to a text file. If the file already exists and the console is not empty, it will be overwritten without warning. Returns True if successful. exc.ConsoleToFile(filename: str): bool filename: The name of the text file the console should be dumped into. The name is expressed according to the current FileNaming property of the SF_FileSystem service. By default, URL notation and the native operating system's format are both admitted. SF_Exception.ConsoleToFile("C:\Documents\myFile.txt") exc.ConsoleToFile(r"C:\Documents\myFile.txt")
DebugDisplay -------------------------------------------------------------------------------------------------------------------------- Exception service;DebugDisplay

DebugDisplay

Concatenates all the arguments into a single human-readable string and displays it in a MsgBox with an Information icon and an OK button. The final string is also added to the Console. exc.DebugDisplay(arg0: any, [arg1: any, ...]) arg0[, arg1, ...]: Any number of arguments of any type. SF_Exception.DebugDisplay("Current Value", someVar) exc.DebugDisplay("Current Value", someVar)
DebugPrint -------------------------------------------------------------------------------------------------------------------------- Exception service;DebugPrint

DebugPrint

Assembles all the given arguments into a single human-readable string and adds it as a new entry in the console. exc.DebugPrint(arg0: any, [arg1: any, ...]) arg0[, arg1, ...]: Any number of arguments of any type. SF_Exception.DebugPrint(Null, Array(1, 2, 3), "line1" & Chr(10) & "Line2", DateSerial(2020, 04, 09)) ' [NULL] [ARRAY] (0:2) (1, 2, 3) line1\nLine2 2020-04-09 exc.DebugPrint(None, [1, 2, 3], "line1\nline2") # None [1, 2, 3] line1\nline2
PythonPrint -------------------------------------------------------------------------------------------------------------------------- Exception service;PythonPrint

PythonPrint

Displays the list of arguments in a readable form in the Python shell (APSO) console. Arguments are separated by a TAB character (simulated by spaces). The same string is added to the ScriptForge debug console. exc.PythonPrint(arg0: any, [arg1: any, ...]) arg0[, arg1, ...]: Any number of arguments of any type. The maximum length of each individual argument is 1024 characters. exc.PythonPrint(a, Array(1, 2, 3), , "line1" & Chr(10) & "Line2", DateSerial(2020, 04, 09)) In python use simply the builtin print() statement.
PythonShell -------------------------------------------------------------------------------------------------------------------------- Exception service;PythonShell

PythonShell

Opens an APSO Python shell as a non-modal window. The Python script keeps running after the shell is opened. The output from print statements inside the script are shown in the shell. Only a single instance of the APSO Python shell can be opened at any time. Hence, if a Python shell is already open, then calling this method will have no effect. exc.PythonShell(variables: dict) variables: a Python dictionary with variable names and values that will be passed on to the APSO Python shell. By default all local variables are passed using Python's builtin locals() function. The example below opens the APSO Python shell passing all global and local variables considering the context where the script is running. exc.PythonShell({**globals(), **locals()}) When the APSO Python shell is open, any subsequent output printed by the script will be shown in the shell. Hence, the string printed in the example below will be displayed in the Python shell. exc.PythonShell() print("Hello world!")
Raise -------------------------------------------------------------------------------------------------------------------------- Exception service;Raise

Raise

Generates a run-time error. An error message is displayed to the user and reported in the console. The execution is stopped. The Raise() method can be placed inside the normal script flow or in a dedicated error-handling routine. SF_Exception.Raise([Number As Variant], [Source As Variant], [Description As String]) The code snippets presented next are equivalent. They show alternative ways to raise an exception with code 2100. SF_Exception.Raise(2100) SF_Exception.Number = 2100 SF_Exception.Raise() SF_Exception.Raise Number := 2100
Number: The error code, as a number or as a string. Default value is that of Err Basic builtin function. Source: The location of the error, as a number or as a string. Default value is that of Erl Basic builtin function. Description: The message to display to the user and to report in the console. Default value is that of Error$ Basic builtin function.
Sub Example_Raise() Dim a, b, c On Local Error GoTo Catch Try: a = 10 : b = 0 c = a / b '... Exit Sub Catch: 'See variants below ... End Sub To raise an exception with the standard values: Catch: SF_Exception.Raise() To raise an exception with a specific code: Catch: SF_Exception.Raise(11) To replace the usual message: Catch: SF_Exception.Raise(, , "It is not a good idea to divide by zero.") To raise an application error: Catch: SF_Exception.Raise("MyAppError", "Example_Raise()", "Something wrong happened !")
RaiseWarning -------------------------------------------------------------------------------------------------------------------------- Exception service;RaiseWarning

RaiseWarning

This method has exactly the same syntax, arguments and behavior as the Raise() method. However, when a warning is raised, the macro execution is not stopped. SF_Exception.RaiseWarning([Number As Variant], [Source As Variant], [Description As String]) SF_Exception.RaiseWarning(Source:="Example_Raise()", _ Description:="Something wrong happened !", _ Number:="MyAppError")