Examples of Arming an Exception Handler

The following two examples show the methods required to arm the exceptionHandler method in the first of the examples under "Examples of Defining an Exception Handler", earlier in this chapter. (For an example of the method that creates an object of the UserException class, defines the properties for this object, and then raises the exception, see "Using the raise exception Instruction", later in this chapter.)

method1();
begin
    // Arms the exception handler so that the exceptionHandler method will
    // be called when an exception of the NormalException class is
    // encountered and will be passed the exception object as a parameter.
    on NormalException do exceptionHandler(exception);
    // causes an exception
    method2;
    status.caption := "Resuming execution after exception throwing method
                      invocation";
end;

method3();
begin
    // Arms the exception handler so that the exceptionHandler method will
    // be called when an exception of the UserException class is raised and
    // will be passed the exception object as a parameter.
    on UserException do exceptionHandler(exception);
    method4;
end;

The following is an example of a method on a Document class that writes the document to a file and arms a local exception handler to catch file exceptions.

writeToFile();
vars
    fileSaveDialog : CMDFileSave;
    file           : File;
begin
    on FileException do fileExceptionHandler(exception);
    create fileSaveDialog transient;
    if fileSaveDialog.open = 0 then
        create file transient;
        file.mode     := File.Mode_Output;
        file.fileName := fileSaveDialog.fileName;
        saveToFile(file);
        file.close;
        delete file;
    endif;
epilog
    delete fileSaveDialog;
end;