Evolve catch
clause to enable pattern matching for more compact catch-when
#8490
Replies: 4 comments 1 reply
-
Similar to #8450. |
Beta Was this translation helpful? Give feedback.
-
I have a similar idea to yours. try
{
}
catch switch
{
case IOException e when (e.Message.Length < i):
break;
case when (i < 3):
default:
break;
} |
Beta Was this translation helpful? Give feedback.
-
If the language devs need references there are other languages implementing such idea. For instance, Nemerle: https://github.com/rsdn/nemerle/wiki/Quick-guide#user-content-TryCatchFinally |
Beta Was this translation helpful? Give feedback.
-
Thank you for bringing similar proposals to my attention. The way this proposal can be different, and what my original intention was, to bring value to the language in the smallest, compatible, incremental way without breaking the original Looking at the language specification: specific_catch_clause
: 'catch' exception_specifier exception_filter? block
| 'catch' exception_filter block
;
exception_specifier
- : '(' type identifier? ')'
+ : '(' (type identifier? | pattern) ')'
; (Based on the Patterns section in the documentation, I'm not sure which is the best choice, but I hope you get the idea.) |
Beta Was this translation helpful? Give feedback.
-
Motivation
It is quite a common pattern to narrow down a
catch
clause based on theException
properties:Compatibility
The way this proposal may be different from others, and what my original intention is to bring value to the language in the smallest, compatible, incremental way without breaking the original
try-catch-finally
statement structure or introducing different syntaxes other than what we already have.try-catch
statement, not expressionAlso, this proposal focuses on improving the
try-catch
statement, at the statement level, so it can be used in existing control flow, and not at the expression level, like theswitch
expression.Description
The
catch
clause is already pattern-like, because it can behave either as a type filter, or a type filter and a declaration as well.The
when
clause was quite useful on its own, but today in many cases these two clauses could be merged into a more powerfulcatch
clause, where not only declaration is allowed, but a pattern:So, this example is equivalent to the first one, but in a more compact form using a pattern in the
catch
clause without awhen
clause.The
when
clause could still remain for narrowing down the filter further if non-constant evaluation is necessary.Detailed design
In language specification:
exception_specifier
inside aspecific_catch_clause
could be replaced to apattern
/declaration_pattern
.Open questions
Beta Was this translation helpful? Give feedback.
All reactions