Let's improve D's exceptions

Jacob Carlborg via Digitalmars-d digitalmars-d at puremagic.com
Thu May 14 03:12:22 PDT 2015


On 2015-05-14 00:55, Steven Schveighoffer wrote:

> enforce is one of the most needless pieces of phobos:
>
> enforce(cond, message);
> vs.
> if(!cond) throw new Exception(message);
>
> And the second doesn't mess up inlining.
>
> I think enforce could be boiler-plated better. The only verbose part of
> the if version is the throwing and newing.
>
> template throe(Etype = Exception)
> {
>     void throe(Args...)(Args args, string file = __FILE__, size_t line =
> __LINE__)
>     {
>         throw new Etype(args, file, line);
>     }
> }
>
> if(!cond) throe(message);

Now you're back to the same problem as "enforce" has. That it throws 
Exception by default. It shouldn't have a default value for the 
exception type.

BTW, it could be called "raise" as it's called in some other languages.

> Wait, you're in an io package, and you want to always throw IO exceptions?
>
> alias except = throe!IOException;
>
> if(!cond) except(args, to, ioexception);

That is a bit better but I still think that IOException is too generic. 
Streaming something over the network and trying to open a file is quite 
different.

> Sure, it doesn't return the thing that caused the exception if nothing
> happens. Grepping phobos, this feature is used with enforce about 1% of
> the time. In fact, I didn't even know it had that feature until looking
> it up in the docs just now.
>
> -Steve


-- 
/Jacob Carlborg


More information about the Digitalmars-d mailing list