[fpc-pascal]exception handling issue

Michalis Kamburelis michalis at camelot.homedns.org
Mon Aug 30 03:12:02 CEST 2004


Hi

Your problem is the consequence of how ReadLn(Longint) works. When you 
enter 'g' + Enter, ReadLn reads 'g', then ReadLn raises runtime error 
(this causes EInOutError exception),  but Enter is still left unread (it 
stays in internal Input buffer). That's why the next ReadLn ("ReadLn 
(tmpLabel);") returns immediately (and sets tmpLabel to '').

Simplest workaround is to not use ReadLn(Longint), use only 
ReadLn(String) and do convertion String -> LongInt explicitly. Like this:

   tmpNumTracksStr: AnsiString;

   ...

   ReadLn (tmpNumTracksStr);
   Try
     tmpNumTracks := StrToInt(tmpNumTracksStr);
   Except
     On E: EConvertError do tmpNumTracks := 0;
   End;

   ...

or even simpler:

   ReadLn (tmpNumTracksStr);
   tmpNumTracks := StrToIntDef(tmpNumTracksStr, 0);

-- 
Michalis

kractor wrote:
> having some problems with exception handling that have me pretty 
> confused .... i'll include below the entire procedure where the 
> exception handling occurs ...
> 
>     Procedure procAddNewAlbum;
>         Var
>             tmpAlbumName : AnsiString;
>             tmpAlbumID : Longint;
>             tmpNumTracks : Smallint;
>             tmpLabel : AnsiString;
>             tmpYear : Integer;
>         Begin
>             Write ('album name: ');
>             ReadLn (tmpAlbumName);
>             tmpAlbumID := ID_Generator;
>             Write ('tracks: ');
>             Try
>                 ReadLn (tmpNumTracks);
>             Except
>                 On E: EInOutError do tmpNumTracks := 0;
>             End;
>             WriteLn ('tmpNumTracks = ',tmpNumTracks);
>             Write ('label: ');
>             ReadLn (tmpLabel);
>             Write ('year: ');
>             Try
>                 ReadLn (tmpYear);
>             Except
>                 tmpYear := 0;
>             End;
>         End;
> 
> now, if i enter anything for tmpNumTracks that's not numeric (and 
> therefore raises the exception) the following happens ...
> 
>     album name: test
>     tracks: g
>     tmpNumTracks = 0
>     label: year: ^C
> 
> the exception code appears to be executed, but when the program "exits" 
> the exception block it seems to be processing one line, then skipping 
> one, then proceeding as normal ... i don't *think* i've made any syntax 
> mistakes, and if i have i'm going to look rather silly ... :D
> 
> _______________________________________________
> fpc-pascal maillist  -  fpc-pascal at lists.freepascal.org
> http://lists.freepascal.org/mailman/listinfo/fpc-pascal
> 




More information about the fpc-pascal mailing list