Exception Safe Programming
Saaa
empty at needmail.com
Sun Feb 25 10:51:39 PST 2007
> Saaa wrote:
>> Maybe I still don't get it :/
>>
>> I made this simple function (mostly stolen :)
>>
>> void getPictureList(char[] dir, out char[][] files){
>> isdir(dir);
>> files = std.file.listdir(dir, "*.png");
>>
>> foreach (d; files)
>> writefln(d);
>> writefln(files.length);
>> //if(files.length < 12) throw new Exception("Not enough images
>> found(<12)");
>> }
>>
>> When I uncomment the last line I get:
>> Error: pictures: The system cannot find the file specified.
>> (commented version doesn't generate any errors)
>>
>> There are only 10 files so an exception should be trown, but not that one
>> ! : )
>
> Somewhere in your program you're trying to open a file called "pictures"
> which is non-existent (at least where the system is looking) causing an
> exception.
Yes the dir is 'pictures', but the program runs perfectly with that last
line commented out. ?
I'd expect it to say:
Error: Not enough images found(<12)
>
>>
>> I call the function in my main and at the end of my main there is:
>>
>> scope(failure)
>> {
>> writefln("Press the 'any' key to quit");
>> getchar();
>> }
>>
>> Why isn't this run in the uncommented version?
>
> Scope guards are excecuted in the reverse order of where they're declared.
> E.g., using the thrower() function from my last example:
>
> void main()
> {
> scope(exit) { writefln(); } //newline
> scope(failure)
> {
> writef("scope guards."); //Note: writef (no ln) doesn't add '\n'
> }
> scope(failure)
> {
> writef("of ");
> }
> scope(failure)
> {
> writef("an example ");
> }
> thrower();
> scope failure(failure)
> {
> writef("This is ");
> }
> }
>
> This will print:
>
> an example of scope guards.
:)
Thanks again. Somehow I keep thinking of scope failure an a property of the
scope. But that analogy only works if the scope failure is actually read. I
had it at the end of my main (never read :)
More information about the Digitalmars-d-learn
mailing list