Comparing Exceptions and Errors
Paul Backus
snarwin at gmail.com
Sat Jun 4 14:05:14 UTC 2022
On Saturday, 4 June 2022 at 11:57:32 UTC, kdevel wrote:
> 2. Since 2017 or so I have written some 10 KLOC of D, maybe
> about two dozen
> classes deriving from Exception. But I did not annotate any
> of my methods or
> function with "nothrow" nor did I author any class deriving
> from `Error`.
>
> What does that mean? Am I `Error` blind?
Generally you do not need to subclass `Error` yourself. The most
common way of throwing an `Error` in user code is to use
`assert`, which (with default compiler flags) throws an
`AssertError` on failure. Function contracts and struct/class
invariants work the same way.
> 3. Can you provide some piece of code which *must* throw
> `Error` and cannot
> throw an appropriate Exception?
This is entirely a question of API design. If it should be the
caller's responsibility to check for some condition before
calling the function, then you can throw an `Error` when that
condition does not hold (or more likely, use an `assert` or an
`in` contract to check for it). If it should be the callee's
responsibility to check, you should throw an `Exception` (or use
`enforce`).
More information about the Digitalmars-d-learn
mailing list