Forum > Beginners

If-then-else inside try-finally; "EXCEPT" expected but "ELSE" found... ?

(1/3) > >>

edvard:
OK, I've run into this a couple of times now, and I need to know what the answer is...
If I have a procedure/function that utilizes an object, standard procedure is:


--- Code: ---var
  SomeThing: TSomeType;
Begin // or Procedure, or Function, whatever
  SomeThing := TSomeType.Create;
  Try
    Do stuff;
  Finally
    SomeThing.Free;
  End;
End;
--- End code ---

Right?
Trouble is, if there is an 'If..Then..Else' in the 'Do Stuff' part, it gives me the "EXCEPT" expected but "ELSE" found error.  I've been through the docs, and can't figure what is going on.  I thought at first that the commands in the 'Do Stuff' section was generating an error, which 'Try' would then expect an 'Except' to handle the error, but I made sure that wasn't it.  Perhaps an 'If..Then..Else' inherently generates exceptions due to it's nature?  I don't know.

Here is some test code; try and compile it, and see the error it gives.  Then comment the 'If...' and 'Else...' lines and see what it does.


--- Code: ---program aint_misbehavin;

{$mode objfpc}

uses
  classes;

var
  somevar: tstringlist;

begin
  somevar := tstringlist.create;
  somevar.add('what is this');
  somevar.add('i dont even');
  try
    writeln(somevar[1]);
    if somevar[1] = 'shut up' then
      writeln('take my money');
    else
      writeln('its a trap');
  finally
  somevar.free;
  end;
end.
--- End code ---

If I try to put the 'If..Then..Else' stuff right after 'Finally', it says "END" expected, but "ELSE" found ...

What am I doing wrong?
 %)

typo:
It happens because you put a semicolon before else.

edvard:
How many times do I have to be bitten by this before I understand that Pascal's semicolon rules are of the devil?  >:D

I figured it out, see here:


--- Code: ---writeln('take my money');

--- End code ---

That semicolon isn't supposed to be there in a 'If..Then..Else' statement.  I really wish FPCs error messages were more helpful sometimes...

I'll leave this here as a warning to anyone else who gets bitten by this.  O:-)

EDIT: posted the same time as you did, Typo.  Thanks for the answer though...  8)

typo:
Basically compiler "thinks' that the "if" statement ends on that semicolon and search for "except" or "finally". And it does not reach it, but reaches "else". So it says: "Else instead of Except".

Leledumbo:

--- Quote from: edvard on December 24, 2014, 05:20:01 am ---How many times do I have to be bitten by this before I understand that Pascal's semicolon rules are of the devil?  >:D

--- End quote ---
If you can't bear the rule, always use begin-end for every construct.

Navigation

[0] Message Index

[#] Next page

Go to full version