[fpc-pascal]How to make a constructor failed?
Full_Name
memsom at post.interalpha.co.uk
Fri Aug 23 17:31:20 CEST 2002
Quoting Aitor SantamarĂa Merino <aitor.sm at wanadoo.es>:
> And what is this "fail"? Is it a predefined identifier, similar in
> category to those "exit" and "break"? or would I need to define such
> method?
If you raise an exception at the point 'fail' happent, it will also give you
much the same result...
{ define an exception class }
type
EFileExistsException = class(Exception);
{...}
constructor TMyClass.Create(fn:String);
begin
{ raise an exception in the case that the file exists }
if FileExists(fn) then
raise EFileExistsException.Create('Error, File exists');
end;
{...}
...
try
{ instantiate class }
X := TMyClass.Create('c:\aaabbbcc.txt'); //this may fail...
try
{ Use try..finally, be nice, protect our resources }
//do whatever with object instance
finally
{ remember to clean up }
X.Free;
end;
except
{ handle exception, names so that we don't just trap everything...
this code should only happen if the constructor fails, unless we reuse
the exception class }
on E: EFileExistsException do begin
//handle the error in some way...
writeln(E.Message);
{ X should still be instanciated, so we must free, but as a precaution
use Assigned() to check that assumption }
if Assigned(X) then X.free;
end;
end;
...
That's how I'd do it. It's less of a kludge than attempting to hide public
members behind a fake constructor. This would probably need to be compiled in
Delphi mode before anyone cries about it not working ;-)
Hope that helps, anyway,
Matt
--
"Computer games don't affect kids; I mean if Pac-Man affected us as kids,
we'd all be running around in darkened rooms, munching magic pills and
listening to repetitive electronic music."
Kristian Wilson,
Nintendo, Inc, 1989
-----BEGIN GEEK CODE BLOCK-----
Version: 3.12
GCS d? s+++:+ a- C++ UL+ P L++ E---- W- N+ o+ K- w
O- M V PS PE-- Y PGP- t- 5-- X- R- tv+ b+ DI++ D+
G e++ h--- r+++ y+++
------END GEEK CODE BLOCK------
More information about the fpc-pascal
mailing list