C# KeyNotFoundException信息
我有一个C#Silverlight应用程序,它随机抛出一个“C# KeyNotFoundException信息,c#,silverlight,C#,Silverlight,我有一个C#Silverlight应用程序,它随机抛出一个“KeyNotFoundException”。我不知道找不到什么钥匙。这就引出了两个问题: KeyNotFoundException是否存储/公开它试图查找的密钥?当我查看数据库时,我没有看到任何暗示此信息可用的信息 我正在通用Application.UnhandledException事件处理程序中捕获/记录此异常。我的问题是,如果我在这里捕捉到事件,我是否可以将ExceptionObject转换为KeyNotFoundExceptio
KeyNotFoundException
”。我不知道找不到什么钥匙。这就引出了两个问题:
KeyNotFoundException
是否存储/公开它试图查找的密钥?当我查看数据库时,我没有看到任何暗示此信息可用的信息非常感谢你的帮助 我认为发现问题的最佳方法是在Application.UnhandledException方法中记录给定异常的StackTrace。通过StackTrace,您可以找到问题的根源(方法的名称、导致异常的文件的名称和行)。这样,您就可以理解代码的错误。
始终尽可能多地记录日志。当给定键不存在时,试图从具有给定键的字典中获取值会导致
KeyNotFoundException
。例如:
var dictionary = new Dictionary<string, string>();
var val = dictionary["mykey"];
private void Application_UnhandledException(object sender,
ApplicationUnhandledExceptionEventArgs e)
{
var stackTrace = e.ExceptionObject.StackTrace;
//Log the stackTrace somewhere.
}
您可以查看它们的KeyNotFoundException
的StackTrace
属性,以确定问题发生的确切位置。所有异常都具有StackTrace
属性,因此您无需关心全局错误处理程序中的异常类型。例如:
var dictionary = new Dictionary<string, string>();
var val = dictionary["mykey"];
private void Application_UnhandledException(object sender,
ApplicationUnhandledExceptionEventArgs e)
{
var stackTrace = e.ExceptionObject.StackTrace;
//Log the stackTrace somewhere.
}
或者,如果您想知道它是什么类型的异常:
private void Application_UnhandledException(object sender,
ApplicationUnhandledExceptionEventArgs e)
{
if (e.ExceptionObject is KeyNotFoundException)
{
//This was a KeyNotFoundException
}
}
当字典抛出
KeyNotFoundException
时,它不会试图告诉您它试图查找的键。正因为如此,我通常尝试在我的字典上使用扩展方法,这样,如果我的程序中断,我就知道它试图查找什么键。虽然知道堆栈跟踪是有帮助的,但这通常是不够的,尤其是在循环内进行查找时
public static TValue GetOrThrow<TKey,TValue>(this IDictionary<TKey,TValue> d, TKey key)
{
try
{
return d[key];
}
catch(KeyNotFoundException ex)
{
throw new KeyNotFoundException(key.ToString()
+ " was not found in the dictionary");
}
}
此外,我发现,将特定的键值放入异常消息中会使在日志中聚合异常变得困难,这取决于您使用的工具类型。(我正在使用一个通过外部异常的消息对错误进行分组的程序)。如果这影响到您,您可能希望将详细信息放入内部异常中:
抛出新的KeyNotFoundException(
“找不到密钥”,
新的KeyNotFoundException(serializedKey));
这是因为silverlight for windows phone不支持wsHttpBinding,所以您可以将服务更改为basicHttpBinding,它将正常工作您应该记录堆栈跟踪,以便查看错误的来源。最相关的答案是。