switch-case-catch
Omar Aloraini
aloraini.omar at gmail.com
Tue Jul 20 06:01:14 UTC 2021
Hello,
With the introduction of sealed hierarchies and the enhancement of switch
expressions, I find myself wondering about the way I model errors.
Previously using a class `Result<T>` to model success or failure of an
operation was something that I used to do, but I quickly reverted as all my
code base methods returned the `Result` type, sometime I introduce another
type to model the error type such as Result<T,E>, where E is typically a
subtype of Exception. But again things get cumbersome, fortunately we now
have sealed hierarchies, which allows us to model multiple possible
outcomes of an operation, or a closed set of error conditions. Client code
is not ugly anymore as switch expressions and pattern matching amend it to
become more concise and pleasant to read and write, or as someone whom I
respected would say ‘less ceremony’. Now I find myself wondering why not
use Exceptions? For some method A that returns a value of type *T* or
throws an exception of two possible types, something like `T A() throws
E1,E2`, obviously you will lose that pleasant client code with switch and
pattern matching. But what if we had switch-case-catch where the catch
clauses must cover all exceptions in the throws clause for it to compile.
Something like the following:
Object r = switch (o.A()){
case T t -> ...
catch E1 e -> ...
catch E1 e -> ...
}
Semantically it would equivalent to:
Object r;
try {
r = switch (o.A()) {
case T t -> ...
} catch (E1 e) {
r = ...
} catch (E2 e) {
r = ...
}
}
You will also get the benefit of pattern matching for the catch clause,
something like `catch E1 | E2`.
I don't think it's necessary to use the `catch` keyword, `case` might just
work.
Apologies if this was suggested before.
More information about the amber-spec-comments
mailing list