Why exceptions for error handling is so important

via Digitalmars-d digitalmars-d at puremagic.com
Fri Jan 16 04:30:10 PST 2015


On Friday, 16 January 2015 at 00:59:34 UTC, deadalnix wrote:
> 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.

IMO, this example just shows that it's a bad idea to follow the 
"exceptions are for exceptional circumstances only" mantra too 
strictly. The call to `file_exists()` serves no other purpose 
than to make the exception truly exceptional, otherwise it's 
completely superfluous (well, aside from performance concerns, 
but these are implementation details). Simply leave it out and 
only rely on the exception, it really isn't evil.


More information about the Digitalmars-d mailing list