KeyConverter does not throw NotSupportedException on undefined values
- Dominant language
- C#
- Stars
- 7.7k
- Forks
- 1.3k
- Avg merge
- 1d 11h
- Merged PRs (30d)
- 61
Description
### Description
`KeyConverter`, unlike `ModifierKeysConverter` and `MouseActionConverter` for example, does not throw `NotSupportedException` but throws `ArgumentException` instead due to the usage of `Enum.Parse` instead of `Enum.TryParse`.
This results in a dead-code being present with proper exception (`key` can never be `null`):
https://github.com/dotnet/wpf/blob/cc0762825f0aff982e785cdbe6db16d747a43910/src/Microsoft.DotNet.Wpf/src/WindowsBase/System/Windows/Input/KeyConverter.cs#L89-L97
It is also the exception that is documented:
https://learn.microsoft.com/en-us/dotnet/api/system.windows.input.keyconverter.convertfrom
### Reproduction Steps
Create `KeyConverter` instance, try to from string with a key that is not defined in the enum, e.g. "MyAmazingKey".
### Expected behavior
We will receive `NotSupportedException` with `SR.Unsupported_Key` message.
### Actual behavior
We receive `ArgumentException` originating from `Enum.Parse`.
### Regression?
Nope, has been the case since NetFX but it is inconsistent and undocumented.
### Impact
Unexpected exception for `TypeConverter` is thrown.
### Next Steps
I plan to submit a PR fixing this behavior, simply by using `TryParse` instead for the fallback.
Contributor guide
Assessment
This issue has not been assessed yet.