$ TryStatement = TRY StatementSequence
[EXCEPT ExceptionHandle]
[FINALLY StatementSequence] END TRY ";"
$ ExceptionHandle = ExceptionBlock [ExceptionBlock] [ELSE StatementSequence]
$ ExceptionBlock = ON { ident ":" } ClassType DO StatementSequence
The Try … Except … Finally … End Try statement is used to process exceptions occurring during the 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 is thrown. 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 base 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 always executed regardless of the fact whether an error occurs when executing statements following the Try keyword, whether the error is handled by the Except block, the Except On block or theElse block or whether the Return statement has been called in any block following Try.
Sub Main;
Var
a: Array[0..1] Of 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: