c# - KeyNotFoundException info -
i have c# silverlight application randomly throwing "keynotfoundexception". have no idea key cannot found. has lead me 2 questions:
- does
keynotfoundexceptionstore/expose key tried find? when looked in documentation, did not see implied information available. - i catching/logging exception in general application.unhandledexception event handler. question is, if catch event here, can convert exceptionobject keynotfoundexception , still key information if exposed asked in #1?
thank help!
a keynotfoundexception caused trying value out of dictionary given key when key not present. example:
var dictionary = new dictionary<string, string>(); var val = dictionary["mykey"]; you can @ of places dictionary being used , determine yourself. general best practice if looking value in dictionary might not present use trygetvalue. catching exception every time more expensive operation , unnecessary:
string val; if(dictionary.trygetvalue("mykey", out val)) { //the key found. value in val. } else { //the key not present. } you can @ stacktrace property of keynotfoundexception determine problem happening. exceptions have stacktrace property, don't need care type of exception in global error handler. example:
private void application_unhandledexception(object sender, applicationunhandledexceptioneventargs e) { var stacktrace = e.exceptionobject.stacktrace; //log stacktrace somewhere. } or, if want able tell type of exception is:
private void application_unhandledexception(object sender, applicationunhandledexceptioneventargs e) { if (e.exceptionobject keynotfoundexception) { //this keynotfoundexception } }
Comments
Post a Comment