A couple questions about a simple project
Ali Çehreli via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Mon Aug 17 10:24:46 PDT 2015
On 08/17/2015 10:08 AM, Andre Polykanine via Digitalmars-d-learn wrote:
> string s;
> try {
> s =
cast(string)std.file.read(f);
> try {
> check(s);
> if (this.verbose) {
>
output(format("%s: validation passed!", f));
> }
> } catch(CheckException e) {
> // This is output when a file is invalid, that works
>
output(format("Failed to validate %s: %s", f, e.toString()));
> }
> } catch(Exception exc) {
> // And that isn't output, I see just the stacktrace as if the
> exception was not caught at all
> output(format("Error reading
%s: %s", f, exc.msg));
> }
> }
Regardless of whether it is the best solution here, you can have
multiple catch blocks for a single try:
try {
// ...
} catch(CheckException e) {
// ...
} catch(Exception exc) {
// ...
}
> To catch the exception, I need to wrap the validate() call in
> `try...catch` in `main()`. Why so?
The reason is you don't try to make use of the provided file name until
validate() starts executing. If it's important that the program notify
the user right away, then you can call std.file.exists() to make sure
that the file is there. Still, it does not try to open so it can't know
whether the file will be readable later.
The funny thing is, even though the upfront check sees a file as being
present, it may disappear when it is being used or it may become unreadable.
A better solution may be to open the files first and then pass File
objects to validate().
> Thanks!
And thank you very much for the kind words! :)
Ali
More information about the Digitalmars-d-learn
mailing list