Exception/Error division in D

Jonathan M Davis jmdavisProg at gmx.com
Wed May 30 14:16:18 PDT 2012


On Wednesday, May 30, 2012 15:28:22 Jacob Carlborg wrote:
> On 2012-05-30 12:59, Jonathan M Davis wrote:
> > Yes, which is why it's better to have an Error thrown rather than a halt
> > instruction be executed. But that doesn't mean that any attempt at cleanup
> > is any more valid.
> 
> If you're not supposed to be able to catch Errors then what's the
> difference?

You can catch them to print out additional information or whatever is useful 
to generate more information about the Error. In fact, just what the Error 
gives you is already more useful: message, file, line number, stack trace, etc. 
That alone makes an Error more useful than a halt instruction.

You can catch them to attempt explicit cleanup that absolutely must be done 
for whatever reason (with the knowledge that it's potentially dangerous to do 
that cleanup due to the Error).

You can catch them in very controlled circumstances where you know that 
continuing is safe (obviously this isn't the sort of thing that you do in 
@safe code). For instance, in some restricted cases, that could be done with 
an OutOfMemoryError. But when you do that sort of thing you have to catch the 
Error _very_ close to the throw point and be sure that there's no cleanup code 
in between. It only works when you can guarantee yourself that the program 
state is not being compromised by the Error, and you're able to guarantee that 
continuing from the catch point is safe. That works in some cases with 
AssertError in unit test code but becomes problematic as such code becomes 
more complex.

- Jonathan M Davis


More information about the Digitalmars-d mailing list