2016-09-07 218 views
0

我目前正在得到一个异常抛出,它给出的消息是价值不在预期的范围内。我试图纠正一段代码来抓住这个异常,并压制它 - 我知道问题是什么 - 基本上有人试图用一个不存在的id从列表中拉出一条记录。捕捉异常

任何想法我怎么去捕捉这个?

+0

https://msdn.microsoft.com/en-us/library/0D565esw.aspx –

+0

你应该使用'try-catch',但是你也需要用代码来处理错误。例如,如果你正在阅读一个数组,并且你太过分了,通过你的代码你不应该让它做,而且当数组没有更多的元素时你应该停止。 'try-catch'应该用于由用户产生的异常,而不是由代码产生。 – Justplayit94

+0

您应该至少在某处记录异常。例外情况不是为了好玩。 – Werner

回答

2

要压制你需要做这样的事情

try 
{ 
    // Code that may throw an exception. 
} 
catch (Exception ex) // Better to use a more specific exception class 
{ 
    // Do nothing - That suppresses the exception. 

    // If you want to do additional checking that may continue the exception 
    // up the stack use "throw" on its own - which compiled to CIL/MSIL's 
    // "rethrow" and doesn't drop much of the information that would 
    // go if you did "throw ex" 
} 

这是一个例外,所有有抑制异常。

为了保持这些代码的完整性(或者你在6个月内忘记了为什么要这样做的具体细节),也很好地评论你为什么要抑制异常。如果我看到抑制异常的代码,我总是想知道为什么。

0

使用trycatch块为空catch?如果你想得到真正的具体信息,你可以使用一个异常过滤器来捕捉这种情况(当然在c#6中)。