Home > Mobile >  Use of semicolons with if/else and try/finally blocks
Use of semicolons with if/else and try/finally blocks

Time:02-11

I have found that this code compiles both with and without a semicolon at the places pointed out below.

What is the correct way to use semicolons here?

  try
    try
      if MyBoolean = True then
      begin
        DoSomething;
      end
      else
      begin
        DoSomethingElse;
      end <<<--- Semi colon here?
    except
      ;
    end <<<--- Semi colon here?
  finally
    ;
  end;

CodePudding user response:

This is documented behavior:

Declarations and Statements (Delphi): Compound Statements

A compound statement is a sequence of other (simple or structured) statements to be executed in the order in which they are written. The compound statement is bracketed by the reserved words begin and end, and its constituent statements are separated by semicolons. For example:

begin
  Z := X;
  X := Y;
  X := Y;
end;

The last semicolon before end is optional. So this could have been written as:

begin
  Z := X;
  X := Y;
  Y := Z
end;

And also:

Delphi's Object Pascal Style Guide: Statements

Statements are one or more lines of code followed by a semicolon. Simple statements have one semicolon, while compound statements have more than one semicolon and therefore consist of multiple simple statements.

Here is a simple statement:

A := B;

If you need to wrap the simple statement, indent the second line two spaces in from the previous line. Here is a compound, or structured, statement:

begin
  B := C;
  A := B;
end;

Compound Statements always end with a semicolon, unless they immediately precede an end keyword, in which case the semicolon is optional but recommended by this style guide.

An "end keyword" in your example would include except and finally.

  • Related