The Try … Except … Finally … End Try Statement

Syntax

$ TryStatement = TRY StatementSequence

[EXCEPT ExceptionHandle]

[FINALLY StatementSequence] END TRY ";"

 

$ ExceptionHandle = ExceptionBlock [ExceptionBlock] [ELSE StatementSequence]

 

$ ExceptionBlock = ON { ident ":" } ClassType DO StatementSequence

Description

The TryExceptFinallyEnd Try statement is used to handle exceptions occurring during program execution.

The Try keyword is followed by the block, executing which may throw an exception. The Except block is executed when an exception is thrown. This block may contain a code block executed if an exception occurs. This block may also contain the On...Do blocks. These blocks are sets of statements starting from the On keyword, which is followed by the type of the handled exception: variable name, colon and variable type - class of handled exception. The specified variable will be used to access information about the exception.

NOTE. The exception class and not the interface describing this class properties can be specified as a variable type. If exception class is unknown, the Exception basic class is specified. The list of exception classes available for use is given in the System Classes of Exceptions subsection.

The code block for handling exceptions is followed by the Do keyword.

The Else phrase (if any) is followed by the sequence of statements, which need to be executed when all other exceptions are handled.

The Finally block is used to force execution of a specific statements sequence when exiting the Try ... End Try block regardless of the results of its execution. This block is executed always regardless of whether an error occurred on execution of statements specified after the Try keyword, whether an error is handled by some Except, Except On, Else block or in one of the blocks following after the Try keyword, whether the Return statement is called.

Example

Sub Main;
Var
    a: Array[0..1Of Integer;
    f: IFileStream;
Begin
    Try
        a[2] := 1;
    Except On e: IndexOutOfRangeException Do
        Debug.WriteLine(e.Line);
        Debug.WriteLine(e.Source);
        Debug.WriteLine(e.Message);
    End Try;
    Try
        f := File.Open("c:\fileabcxyz666.txt", FileOpenMode.Read, FileShare.Exclusive);
    Except On e: FileNotFoundException Do
        Debug.WriteLine(e.Line);
        Debug.WriteLine(e.Source);
        Debug.WriteLine(e.Message);
    Finally
        Debug.WriteLine("This block is always executed");
    End Try;
End Sub Main;

After executing the example two exceptions are handled that occur when an element with an invalid index or a missing file is being called. When an exception is handled, the development environment console displays the error text, the unit or form identifier and the string number on execution of which the error occurs.

See also:

Statements

Handling Exceptions

Raise