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

Mike Parker aldacron at gmail.com
Mon Feb 25 02:39:25 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

These days you can disable the check on final switches:

-check=switch=off

However, in this case, I would say you should actually be using a 
normal switch because your input is not an enum and you aren't 
constraining its value. IMO, using any type other than an enum as 
the input for a final switch should be a compiler error.


More information about the Digitalmars-d-learn mailing list