Why exceptions for error handling is so important

deadalnix via Digitalmars-d digitalmars-d at puremagic.com
Thu Jan 15 16:59:33 PST 2015


On Thursday, 15 January 2015 at 21:48:25 UTC, Tobias M wrote:
> Example:
> Creating a file: Throws if already exists.
> Creating a unique filename:
> Create file.1.exp
> Create file.2.exp
> Create file.3.exp
> ... until it succeeds.
> Here failure is expected and normal, still trial/error is the 
> only option because a querying the file first is not safe.
>
> How can I (as the implementer of the "Create file" function) 
> decide if a failure is actually expected or not?
> I can't, because I cannot foresee every use case of the 
> function.
>
> *Especially* with environmental errors that caller has to 
> decide what's an error and what not.
> You cannot just require certain environmental preconditions, 
> because they can change unexpectedly.

auto create_unique_file() {
   for (uint i = 0;; i++) {
     auto name = make_name(i);
     if (file_exists(name)) continue;

     try {
       create_file(name);
       return name:
     } catch(FileAlreadyExistException e) { }
   }
}

You don't need 2 interfaces, the only time when the Exception is 
going to fire, is if the file is created between the file_exists 
check and the actual creation: almost never.


More information about the Digitalmars-d mailing list