Checked vs unchecked exceptions
Moritz Maxeiner via Digitalmars-d
digitalmars-d at puremagic.com
Tue Jun 27 19:09:40 PDT 2017
On Wednesday, 28 June 2017 at 01:35:32 UTC, mckoder wrote:
> On Tuesday, 27 June 2017 at 22:56:47 UTC, Moritz Maxeiner wrote:
>>
>> You mean the very first time you want to call it and you don't
>> know the exception set yourself by looking at its signature?
>> Put the call in a nothrow scope and compile the module (which
>> is fast in D), the compiler will then complain which
>> exceptions you didn't catch (requires improvement of nothrow
>> analysis [1]).
>>
>
> So to know what exceptions are possible you have to compile the
> code?
That, or do the even faster thing and use what's written in the
documentation (which a sensible person might generate
automatically, embedding the generated exception set for each
function).
There are only two outcomes (sans compiler bugs):
- What's written there is correct -> It will compile and you're
fine
- What's written there is incorrect -> It won't compile and tell
you what's missing
In the 2nd case you have discovered a bug in whatever codebase
you are using. Report it.
> I consider that inferior to other solutions such as callee
> explicitly stating what exceptions it may throw, because then
> all you have to do is glance at the callee.
On the one hand you have a small one-time cost (I would go as far
as calling it tiny, since I consider it a reasonable assumption
for you to have the documentation open), on the other hand you
have a one-time cost with its size depending on the call
hierarchy level and small constant maintenance costs on every
change.
If you consider the first inferior to the second, that's your
call, but I disagree strongly.
That being said, nothing prevents you from putting it there
anyway:
---
static assert (throwsExactly!(foo, AException, BException));
void foo() { ... }
---
> Also, I think explicitly stating your intent in this manner
> (by the callee not just the caller) is a good idea, to make
> sure you are not throwing some exception you didn't mean to
> throw.
Add a static assert as shown above and you're done.
More information about the Digitalmars-d
mailing list