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.

tip

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:

  1. Report the error in the Exception console

  2. Inform the user about the error using either a standard message or a custom message

  3. 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.

note

Not all methods and properties are available for Python scripts since the Python language already has a comprehensive exception handling system.


Service invocation

In Basic

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(...)
  
In Python

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.


tip

Raising or clearing an Exception resets its properties.


note

Error code range 0-2000 is reserved for Collabora Office Basic. User-defined errors may start from higher values in order to prevent collision with Collabora Office Basic future developments.


List of Methods in the Exception Service

Clear
Console
ConsoleClear

ConsoleToFile
DebugDisplay
DebugPrint

PythonPrint
PythonShell
Raise
RaiseWarning


Clear

Resets the current error status and clears the SF_Exception properties.

note

This method is only available for Basic scripts.


Syntax:


    SF_Exception.Clear()
  

Example:

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
  
tip

For a complete list of Basic run-time error codes, refer to Debugging a Basic Program.


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.

Syntax:

exc.Console(modal: bool = True)

Parameters:

modal: Determine if the console window is modal (True) or non-modal (False). Default value is True.

Example:

In Basic

        SF_Exception.Console(Modal := False)
  
In Python

    exc.Console(modal = False)
  

ConsoleClear

Clears the console keeping an optional number of recent messages. If the console is activated in non-modal mode, it is refreshed.

Syntax:

exc.ConsoleClear(keep: int = 0)

Parameters:

keep: The number of recent messages to be kept. Default value is 0.

Example:

The following example clears the console keeping the 10 most recent messages.

In Basic

        SF_Exception.ConsoleClear(10)
  
In Python

    exc.ConsoleClear(10)
  

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.

Syntax:

exc.ConsoleToFile(filename: str): bool

Parameters:

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.

Example:

In Basic

        SF_Exception.ConsoleToFile("C:\Documents\myFile.txt")
  
In Python

    exc.ConsoleToFile(r"C:\Documents\myFile.txt")
  

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.

Syntax:

exc.DebugDisplay(arg0: any, [arg1: any, ...])

Parameters:

arg0[, arg1, ...]: Any number of arguments of any type.

Example:

In Basic

    SF_Exception.DebugDisplay("Current Value", someVar)
  
In Python

    exc.DebugDisplay("Current Value", someVar)
  

DebugPrint

Assembles all the given arguments into a single human-readable string and adds it as a new entry in the console.

Syntax:

exc.DebugPrint(arg0: any, [arg1: any, ...])

Parameters:

arg0[, arg1, ...]: Any number of arguments of any type.

Example:

In Basic

    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
  
In Python

    exc.DebugPrint(None, [1, 2, 3], "line1\nline2")
    # None  [1, 2, 3]  line1\nline2
  

PythonPrint

Displays the list of arguments in a readable form in the platform console. Arguments are separated by a TAB character (simulated by spaces).

The same string is added to the ScriptForge debug console.

If Python shell (APSO) is active, PythonPrint content is written to APSO console in place of the platform console.

note

This method is only available for Basic scripts.


Syntax:


  exc.PythonPrint(arg0: any, [arg1: any, ...])
  

Parameters:

arg0[, arg1, ...]: Any number of arguments of any type. The maximum length of each individual argument is 1024 characters.

Example:


    exc.PythonPrint(a, Array(1, 2, 3), , "line1" & Chr(10) & "Line2", DateSerial(2020, 04, 09))
  
note

In Python use a print statement to print to the APSO console or use the DebugPrint method to print to ScriptForge's console.


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.

warning

This method requires the installation of the APSO (Alternative Script Organizer for Python) extension. In turn APSO requires the presence of Collabora Office Python scripting framework. If APSO or Python are missing, an error occurs.


Syntax:

exc.PythonShell(variables: dict)

Parameters:

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.

Example:

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

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.

note

This method is only available for Basic scripts.


Syntax:


    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
  

Parameters:

Number: The error code, as a number or as a string. Default value is that of Err Basic builtin function.

note

Error code range 0-2000 is reserved for Collabora Office Basic. User-defined errors may start from higher values in order to prevent collision with Collabora Office Basic future developments.


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.

Example:


    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

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.

note

This method is only available for Basic scripts.


Syntax:


    SF_Exception.RaiseWarning([Number As Variant], [Source As Variant], [Description As String])
  

Parameters:

Number: The error code, as a number or as a string. Default value is that of Err Basic builtin function.

note

Error code range 0-2000 is reserved for Collabora Office Basic. User-defined errors may start from higher values in order to prevent collision with Collabora Office Basic future developments.


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.

Example:


    SF_Exception.RaiseWarning(Source:="Example_Raise()", _
        Description:="Something wrong happened !", _
        Number:="MyAppError")
  

Please support us!