Tartalom

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

A Exception szolgáltatáskonzol tárolja az eseményeket, a változóértékeket és a hibákra vonatkozó információkat. A konzolt akkor használja, ha a Basic IDE nem könnyen hozzáférhető, például a Calc egyéni függvények (UDF) vagy az események feldolgozása során.

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

A Python parancsfájlokban az Exception szolgáltatást leginkább hibakeresésre használják. Az olyan metódusok, mint a DebugPrint, Console és DebugDisplay hasznosak az üzenetek gyors kinyomtatására, az adatok naplózására és a konzolablak megnyitására egy Python parancsfájlból.

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

## A szolgáltatás igénybevétele

##### A Basic nyelvben

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

##### A Python nyelvben

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()

## Tulajdonságok

The properties listed below are only available for Basic scripts.

Név | Írásvédett | Leírás
--- | --- | ---
Description | Nem | The error message text. Default value is "" or a string containing the Basic run-time error message.
Number | Nem | 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 | Nem | 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.

Error code range 0-2000 is reserved for LibreOffice Basic. User-defined errors may start from higher values in order to prevent collision with LibreOffice 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.

This method is only available for Basic scripts.

### Szintaxis:

        SF_Exception.Clear()

### Példa:

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

A konzolüzenetek megjelenítése modális vagy nem modális párbeszédpanelben. Mindkét módban a DebugPrint() metódus által kiadott vagy kivételből eredő összes múltbeli üzenet megjelenik. Nem modális módban a későbbi bejegyzések automatikusan hozzáadódnak.

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.

### Szintaxis:

exc.Console(modal: bool = True)

### Paraméterek:

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

### Példa:

##### A Basic nyelvben

            SF_Exception.Console(Modal := False)

##### A Python nyelvben

        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.

### Szintaxis:

exc.ConsoleClear(keep: int = 0)

### Paraméterek:

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

### Példa:

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

##### A Basic nyelvben

            SF_Exception.ConsoleClear(10)

##### A Python nyelvben

        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.

### Szintaxis:

exc.ConsoleToFile(filename: str): bool

### Paraméterek:

filename: Annak a szöveges fájlnak a neve, amelybe a konzolt ki kell tölteni. A név a SF_FileSystem szolgáltatás aktuális FileNaming tulajdonságának megfelelően kerül kifejezésre. Alapértelmezés szerint a URL notation és a natív operációs rendszer formátumát egyaránt elfogadja.

### Példa:

##### A Basic nyelvben

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

##### A Python nyelvben

        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.

### Szintaxis:

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

### Paraméterek:

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

### Példa:

##### A Basic nyelvben

        SF_Exception.DebugDisplay("Current Value", someVar)

##### A Python nyelvben

        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.

### Szintaxis:

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

### Paraméterek:

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

### Példa:

##### A Basic nyelvben

        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

##### A Python nyelvben

        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.

This method is only available for Basic scripts.

### Szintaxis:

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

### Paraméterek:

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

### Példa:

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

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

## PythonShell

Megnyitja az APSO Python héjat nem modális ablakként. A Python parancsfájl a héj megnyitása után is fut. A parancsfájlban lévő print utasítások kimenete megjelenik a héjban.

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.

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

### Szintaxis:

exc.PythonShell(variables: dict)

### Paraméterek:

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.

### Példa:

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()})

Ha az APSO Python héja nyitva van, a parancsfájl által kiírt minden további kimenet a héjban jelenik meg. Így az alábbi példában kiírt karakterlánc a Python héjban fog megjelenni.

        exc.PythonShell()
        print("Helló világ!")

## Raise

Futásidejű hibát generál. A hibaüzenet megjelenik a felhasználónak, és a konzolban is megjelenik. A végrehajtás leáll. A Raise() metódus elhelyezhető a normál parancsfájlfolyamban vagy egy külön hibakezelő rutinban.

This method is only available for Basic scripts.

### Szintaxis:

        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

### Paraméterek:

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

Error code range 0-2000 is reserved for LibreOffice Basic. User-defined errors may start from higher values in order to prevent collision with LibreOffice 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.

### Példa:

        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.

This method is only available for Basic scripts.

### Szintaxis:

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

### Paraméterek:

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

Error code range 0-2000 is reserved for LibreOffice Basic. User-defined errors may start from higher values in order to prevent collision with LibreOffice 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.

### Példa:

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

Kapcsolódó témakörök

Error-Handling Functions