我列出了C#winforms应用程序中的所有USB应用程序,并尝试使用脚踏板播放音频。
我收到以下错误。
未处理的类型' System.ArgumentException'发生在 mscorlib.dll中
其他信息:目标数组不够长,无法复制 集合中的所有项目。检查数组索引和长度。
private void ReadProcess(HidReport report)
{
byte[] message = report.Data;
uint _message;
Array.Reverse(message);
_message = BitConverter.ToUInt32(message, 0); // exception here!
....
答案 0 :(得分:1)
如果您只想处理特定的异常,只需使用try/catch
并明确说明您要捕获的异常类型:
try
{
byte[] message = report.Data;
uint _message;
Array.Reverse(message);
_message = BitConverter.ToUInt32(message, 0);
} catch(ArgumentException ex)
{
// Your logic...
}
由于您没有分享确切发生异常的位置,因此我无法确定要检查的内容,但您应尽可能尝试验证参数,并抛出自己的异常或返回特定错误。
答案 1 :(得分:1)
BitConverter.ToUInt32(byte[] value, int startIndex)
抛出 当startIndex大于或等于时,ArgumentException 值的长度减去3,并且小于或等于长度 值减去1。
问题出在report.Data
,因为它不符合要转换的要求。
您始终可以将代码包装在try-catch-finally中并处理异常,但我建议您read more about different type of exceptions and how you should handle them。