Why is SwitchError an error and how is it unsafe to continue after catching it?

Alex sascha.orlov at gmail.com
Sun Feb 24 11:05:31 UTC 2019


On Sunday, 24 February 2019 at 10:53:09 UTC, aliak wrote:
> Because from what I understand, an Error is something you 
> should not be catching and represents something unrecoverable. 
> And it the docs say that it's unsafe to continue execution. But 
> the following code is very recoverable and I don't see how it's 
> unsafe to continue executing:
>
> import optional;
> import core.exception: SwitchError;
>
> enum Enum : string {
>   one = "one", two = "two"
> }
>
> Optional!Enum makeEnum(string value) {
>   try {
>     final switch (value) {
>     case Enum.one: return some(Enum.one);
>     case Enum.two: return some(Enum.two);
>     }
>   } catch (SwitchError) {
>     return no!Enum;
>   }
> }
>
> unittest {
>     assert(makeEnum("one") == some(Enum.one));
>     assert(makeEnum("huh") == no!Enum);
> }
>
> Cheers,
> - Ali

There is a semantic difference between a switch and a final 
switch statement, defined here:
https://dlang.org/spec/statement.html#final-switch-statement

By this difference, the writer of the final switch declares, that 
it is unrecoverable to pass something unexpected to the switch 
statement. The catch of an error as you demonstrated is, 
therefore, a contradiction to the finality of the switch.

I mean, if you know, that something beyond the enum can be 
passed, use a normal switch and handle the case in the default 
section. If you are able to ensure, this case is unreachable, you 
express this knowledge/ability by the final switch and don't need 
the try-catch clause at all.


More information about the Digitalmars-d-learn mailing list