[Vala] How should I handle a constructor that fails?



What should I do in a construct block when the normal thing would be
to throw? Can object instantiation be stopped by an error like in C++
or is the vala way to let construction continue and then set a zombie
flag?

Maybe a static method that creates an object, checks a zombie flag,
and then throws if true could masquerade as the actual constructor.
That's what I would do but it almost seems like a workaround.

Forgive me for having very little experience with both C# and GObject
and therefore lacking the ability to infer something so simple. Is
there a preferred way to signal a failed constructor to the caller?

Here is an example of what I'm talking about.


errordomain IOError {
    FILE_NOT_FOUND
}

class Foo : Object {
        string filename { get; set; }
        public bool failed;

        private Foo.with_file_ (string filename) {
                this.filename = filename;
        }

        public static Foo with_file (string filename) throws IOError {
                var foo = new Foo.with_file_ (filename);
                if (foo.failed) throw new IOError.FILE_NOT_FOUND("Requested file
could not be found.");
                return foo;
        }

        construct {
                this.failed = true;
        }
}

void main () {
        try {
                var foo = Foo.with_file ("test");
                message ("ok");
        }
        catch {
                message ("error");
        }
}



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]