The problem with:
type X = enum
Z
var a = 42
var b = X(a)
Run
is that it raises a RangeDefect exception and that defects are considered non
catchable (in fact, by default, they are, for now…).
The distinction between catchable exceptions and defects have been introduced
because some errors, as division by zero, are really non catchable. But there
are few of them.
For most defects, this has been a design choice. For instance, we could
consider an index out of range as a catchable error rather than a defect. I
don’t say we should, however.
I think that with this conversion, we are in a situation where we could
consider the error to be catchable. Rather than raising a RangeDefect, the
compiler could generate code to raise a ValueError. This is what is done by
parseEnum.
Of course, one can says that it would be inconsistent with the behavior of
other conversions. That’s true but for other conversions it is easy to make
sure that they are possible before actually doing the conversion. This is not
the case for enums, at least when their values are not contiguous.
Another way to keep a consistent behavior should be to change RangeDefect to
Range Error, i.e. to make the exception catchable.
All other solutions consist to try to do manually the check the compiler does,
which is fine except for non contiguous enums.