Recover in Pascal

program RecoverExample;

uses
  SysUtils;

procedure MayRaise;
begin
  raise Exception.Create('a problem');
end;

procedure Main;
begin
  try
    MayRaise;
    WriteLn('After MayRaise()');
  except
    on E: Exception do
    begin
      WriteLn('Recovered. Error:');
      WriteLn(E.Message);
    end;
  end;
end;

begin
  Main;
end.

Pascal makes it possible to recover from exceptions using a try-except block. This mechanism can stop an exception from terminating the program and allow it to continue execution instead.

An example of where this can be useful: a server wouldn’t want to crash if one of the client connections exhibits a critical error. Instead, the server would want to close that connection and continue serving other clients.

In this example, we define a procedure MayRaise that raises an exception:

procedure MayRaise;
begin
  raise Exception.Create('a problem');
end;

To handle exceptions, we use a try-except block in the Main procedure:

procedure Main;
begin
  try
    MayRaise;
    WriteLn('After MayRaise()');
  except
    on E: Exception do
    begin
      WriteLn('Recovered. Error:');
      WriteLn(E.Message);
    end;
  end;
end;

The try block contains the code that might raise an exception. If an exception is raised, execution immediately jumps to the except block. Here, we catch all exceptions of type Exception (which includes all standard exceptions in Pascal).

When an exception is caught, we print a message indicating that we recovered from the error, along with the error message.

The line WriteLn('After MayRaise()'); will not be executed because MayRaise raises an exception. The execution of Main stops at the point of the exception and resumes in the except block.

When you run this program, you should see output similar to this:

Recovered. Error:
a problem

This demonstrates that we successfully caught and handled the exception, preventing it from crashing our program.