[OT] OT: Null checks.

Walter Bright newshound2 at digitalmars.com
Tue May 6 06:11:29 UTC 2025


D is set up so if you throw an `Exception`, then destructors will run as the 
stack unwinds. But if you throw an `Error`, you can catch it but the destructors 
don't run.

The reason is that `Error` means the program has entered an invalid state. 
Nothing in the program can be trusted any more. The program should do as little 
as possible to close down gracefully.

The template `std.exception.enforce` works like `assert`, but throws an 
`Exception` instead.

The documentation for `enforce()` says:

$(NOTE `enforce` is used to throw exceptions and is therefore intended to
aid in error handling. It is $(I not) intended for verifying the logic
of your program - that is what `assert` is for.)

What you can do is override the default assert behavior by inserting your own 
assert handler by calling `core.exception.assertHandler()`. Be sure to set 
`-checkaction=D`

Then you can have assert() behave however you want.


More information about the Digitalmars-d mailing list