[Proposal]: Exception-coalescing operator #9339
Unanswered
zenvin-dev
asked this question in
Language Ideas
Replies: 1 comment 6 replies
-
We are unlikely to do this as catching all exceptions like this is definitely an anti pattern. If you do need this, you could have some exception to help out: public static T DangerousCatchAll<T>(Func<T> func, T @default)
{
try
{
return func();
}
catch
{
return @default;
}
} Now you could say: MyType variable = (() => SomeExpressionThatMayThrow()).DangerousCatchAll(fallbackValue); |
Beta Was this translation helpful? Give feedback.
6 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Summary
Exception-coalescing operators would introduce syntactic sugar for inlining those
try/catch
blocks, whose only function is to catch an exception while invoking the right-hand expression of an assignment operator.Motivation
Currently, there is an entire block of code needed in order to merely assign different values to a variable based on whether an exception occurred:
The variable needs to be declared, and a
try/catch
block needs to be introduced.This is pretty tedious to write, and also annoying to read - more so if it happens to occur several times in a row.
This proposal aims to improve on this, by introducing an operator that makes it possible to shorten this code, similarly to how the null-coalescing operator (
??
) does fornull
-checks.Proposed syntax
There are several way this could be implemented, respectively with different readability and brevity.
The overall syntax would be similar to the null-coalescing operator (
??
):In code, that would look something like this:
Operator considerations
Ideas for possible operators
Symbol
?!
Advantages:
??
), therefore familiarDisadvantages:
Repurpose
catch
keywordAdvantages:
Disadvantages:
Further considerations
Typed exception handling
For maximum usability, the operator should support providing information about the exception that occurred.
In order to do this, the syntax could be expanded as follows:
The
identifier
ofLEFT_PAREN type_name identifier? RIGHT_PAREN
should be available to the expression on the right-hand side of the operator.If the
type_name
constraint of the handled exception does not match the thrown exception, this also needs to be accounted for.Two ways of doing this come to mind:
System.Exception
Since chained
try/catch
blocks will throw if thecatch
has a too-narrow requirement, the former option would likely represent the expected behaviour.Chaining
Just like
try/catch
blocks, exception-coalescing operators should allow chaining in order to account for multiple types of exceptions.This obviously requires typed exception handling, as described above
Beta Was this translation helpful? Give feedback.
All reactions