enforce()?

Jonathan M Davis jmdavisProg at gmail.com
Wed Jun 16 14:28:16 PDT 2010


Ali Çehreli wrote:

> Jonathan M Davis wrote:
> 
>  > Assertions assert that something is _always_ true and that if it
> isn't, the
>  > program is wrong, while exceptions are for exceptional circumstances
> 
> Makes sense.
> 
>  > You use [enforce] when you want an exception thrown rather than when
> you want to
>  > kill your program due to an error.
> 
> To further confuse the issue, assert throws too:
> 
> import std.stdio;
> import std.algorithm;
> 
> void main()
> {
>      try {
>          assert(false);
>      } catch (Throwable) {
>          writeln("an assertion failed");
>      }
> }
> 
> The difference is just the exception that is thrown. Throwable seems to
> be most general.
> 
>  From what I've read so far, I take enforce as a replacement to what it
> exactly is:
> 
> if (condition) {
>      throw /* ... */;
> }
> 
> Since I never use assert for that purpose, I take enforce as a shortcut
> for the above.
> 
> Ali

Well, in a sense, the fact that assertions throw is an implementation detail 
since that's not the case in all languages. The concepts of assertions and 
exceptions are distinctly different.

However, while assertions do throw in D, they throw AssertErrors which are 
Errors and not exceptions, albeit both are Throwable. So, they're still 
different. You _can_ catch Errors, but you probably shouldn't. I believe 
that they're intended for pretty much unrecoverable errors. The fact that 
they're thrown likely makes it easier to exit the program semi-gracefully - 
or at least makes it easier for the generated program to properly indicate 
an error rather than simply dying - but they're still distinctly separate 
from exceptions and shouldn't generally be caught. I suppose that it's kind 
of like the difference between checked and unchecked exceptions in Java. You 
generally only worry about the checked ones.

You are right though in that the fact that Errors are Throwable does muddle 
things somewhat.

- Jonathan M Davis


More information about the Digitalmars-d mailing list