如何处理 'System.ArgumentException' 类型的未处理异常?

How to handle an unhandled exception of type 'System.ArgumentException'?

我正在 C# winforms 应用程序中列出所有 USB 应用程序并尝试使用脚踏板播放音频。

我收到以下错误。

An unhandled exception of type 'System.ArgumentException' occurred in mscorlib.dll

Additional information: Destination array is not long enough to copy all the items in the collection. Check array index and length.

private void ReadProcess(HidReport report)
{
    byte[] message = report.Data;
    uint _message;
    Array.Reverse(message);
    _message = BitConverter.ToUInt32(message, 0); // exception here!
    ....

如果您只是想处理特定的异常,只需使用 try/catch 并明确说明您要捕获的异常类型:

try
{
   byte[] message = report.Data;
   uint _message;
   Array.Reverse(message);
   _message = BitConverter.ToUInt32(message, 0);
} catch(ArgumentException ex)
{
   // Your logic...
}

由于您没有分享异常发生的确切位置,我无法确定要检查的内容,但如果可能,您应该尝试验证参数并抛出您自己的异常或 return 特定错误。

BitConverter.ToUInt32(byte[] value, int startIndex) throws ArgumentException when startIndex is greater than or equal to the length of value minus 3, and is less than or equal to the length of value minus 1.

问题出在report.Data,不符合转换条件

您始终可以将代码包装在 try-catch-finally and handle the exception but I suggest you to read more about different type of exceptions and how you should handle them 中。