scope file.open
Frits van Bommel
fvbommel at REMwOVExCAPSs.nl
Wed Jan 24 06:23:16 PST 2007
Jarrett Billingsley wrote:
> "nobody" <not at possible.de> wrote in message
> news:ep7395$o92$1 at digitaldaemon.com...
>
>> The question is, how scope know it's a failure to open a file, before the
>> file.open statement
>> is executed.
>> That is i didn't understand.
>
> What the scope(failure) statement does is "registers" the following piece of
> code to be executed whenever the current scope (brace block) is left. So
> you can put it anywhere:
1) It only gets executed when the scope is exited by exception unwinding.
2) It only gets executed when that exception happens *after* the scope
statement.
http://www.digitalmars.com/d/statement.html#ScopeGuardStatement
> scope(failure) writefln("Datei kann nicht geoeffnet werden ");
> File file = new File;
> file.open("testdatei.txt",FileMode.In);
> while(!file.eof()) writefln(file.readLine());
> file.close();
That'll work.
> Or:
>
> File file = new File;
> scope(failure) writefln("Datei kann nicht geoeffnet werden ");
> file.open("testdatei.txt",FileMode.In);
> while(!file.eof()) writefln(file.readLine());
> file.close();
That'll only print if 'new File' is successful (i.e. there's enough
memory and the constructor doesn't throw an exception) but an exception
gets thrown in the rest of the code.
> Or even:
>
> File file = new File;
> file.open("testdatei.txt",FileMode.In);
> while(!file.eof()) writefln(file.readLine());
> file.close();
> scope(failure) writefln("Datei kann nicht geoeffnet werden ");
That will *not* work. It's just too late to affect any code.
> It doesn't matter where the scope(failure) appears. It just means "if an
> exception passes out of this block, run this code."
It's "If an exception passes out of this block *after this statement*,
run this code", actually.
See for yourself:
-----
urxae at urxae:~/tmp$ cat test.d
import std.stdio;
void main() {
scope(failure) writefln("will print");
throw new Exception("will be thrown");
scope(failure) writefln("won't print");
}
urxae at urxae:~/tmp$ dmd -run test.d
will print
Error: will be thrown
-----
More information about the Digitalmars-d-learn
mailing list