scope file.open
Frits van Bommel
fvbommel at REMwOVExCAPSs.nl
Tue Jan 23 13:50:54 PST 2007
Chris Nicholson-Sauls wrote:
> nobody wrote:
>> Hallo,
>>
>> how can i saftly open a file with scope.
>> My idea is:
[snip]
>> But why must scope(failure) before the file.open statement.
>> I think it's look strange.
>> Mybe some on have a better idea to open a file with scope.
>
> Personally I don't think it really looks all that strange, but I'm odd
> like that. :) In this case, if it worries you, you might try a
> traditional try-catch-finally instead.
>
> # void main () {
> # File file = new File ;
> #
> # try {
> # file.open("testdatei.txt",FileMode.In);
> # while(!file.eof()) {
> # printf("%.*s\n",file.readLine());
> # }
> # }
> # catch (Exception x) {
> # writefln("Datei kann nicht geoeffnet werden ");
> # throw x;
> # }
> #
> # file.close();
> # }
While you're at it, either
* put 'scope' in front of the 'File file' declaration, or
* move 'file.close()' into a finally{} block at the end of that
try-catch, or
* put 'scope(exit) file.close();' right after the declaration of file
All of those will guarantee your file gets closed if an exception gets
thrown. I'd personally prefer the first one, but if you're going to use
try-catch anyway you might as well tack on a 'finally'.
Of course, it doesn't really matter in this case since it's directly in
main(), and the exception will exit it...
More information about the Digitalmars-d-learn
mailing list