runtime: Proposal: MatchFailureException
Rationale
In order to facilitate the language feature at https://github.com/dotnet/csharplang/issues/45, which has been approved by the LDM and mostly implemented, we should add the exception MatchFailureException
to the framework. This exception is to be thrown when no branch of a pattern-matching switch expression matches the input at runtime.
Proposal
namespace System
{
/// <summary>
/// Indicates that a switch expression that was non-exhaustive failed to match its input
/// at runtime, e.g. in the C# 8 expression <code>3 switch { 4 => 5 }</code>.
/// The exception optionally contains an object representing the unmatched value.
/// </summary>
[System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
public class MatchFailureException : InvalidOperationException
{
public MatchFailureException();
public MatchFailureException(object unmatchedValue);
public object UnmatchedValue { get; }
[System.Security.SecurityCritical]
public override void GetObjectData(SerializationInfo info, StreamingContext context);
}
}
See also https://github.com/dotnet/roslyn/issues/27747 /cc @jcouv @jaredpar
About this issue
- Original URL
- State: closed
- Created 6 years ago
- Comments: 37 (30 by maintainers)
Commits related to this issue
- Add SwitchExpressionException Fixes: #33284 — committed to maryamariyan/corefx by maryamariyan 5 years ago
- Add SwitchExpressionException Fixes: #33284 — committed to maryamariyan/corefx by maryamariyan 5 years ago
- Add SwitchExpressionException Fixes: #33284 — committed to maryamariyan/corefx by maryamariyan 5 years ago
- Add SwitchExpressionException (#34954) * Add SwitchExpressionException Fixes: #33284 * Apply PR feedbacks * Type just added to .net core 3.0 * quick cleanup * Add test in BinaryFormatt... — committed to dotnet/corefx by maryamariyan 5 years ago
I changed the base type to
InvalidOperationException
.@maryamariyan can you please add this new exception next week? Looks like it’s super easy, API is approved, basically no code (like eg
InvalidDataException
) except for this object getter, basic tests to new it up and get/set.@gafter @terrajobst are
[System.Security.SecurityCritical]
and[ComVisible(true)]
both required?SecurityCritical
has no effect in .NET Core and no other exceptions have it. No other exceptions haveComVisible(true)
either.Ah, I missed the inheritance relationship. That addresses my concern.
FWIW, I pushed for this to be included because it can only help with debugging, and in most cases it should be able to include the value (it won’t in corner cases like matching on a ref struct). The value’s ToString would be output as part of Exception’s ToString, similar to how it is for ArgumentOutOfRangeException.
e.g. if it’s something that can’t be boxed, like a
ref struct
I’ve added an (optional)
object unmatchedValue
parameter.