I was wondering if there was a reasonable way to customize messages on exceptions that are thrown by the .NET framework? Below is a chunk of code that I write often, in many different scenarios to achieve the effect of providing reasonable exception messages to my users.
public string GetMetadata(string metaDataKey)
{
// As you can see, I am doing what the dictionary itself will normally do, but my exception message has some context, and is therefore more descriptive of the actual problem.
if (!_Metadata.ContainsKey(metaDataKey))
{
throw new KeyNotFoundException(string.Format("There is no metadata that contains the key '{0}'!", metaDataKey));
}
// This will throw a 'KeyNotFoundException' in normal cases, which I want, but the message "The key is not present in the dictionary" is not very informative. This is the exception who's message I wish to alter.
string val = _Metadata[metaDataKey].TrimEnd();
return val;
}
As you can see, I am essentially producing duplicate code just to use a different (better) message.
Edit:
What I am looking for, essentially is something like this:
KeyNotFoundException.SetMessage("this is my custom message!")
{
// OK, now this will send off the message I want when the exception appears!
// Now I can avoid all of that silly boilerplate!
string val = _Metadata[metaDataKey].TrimEnd();
}
At any rate, i don't think that such a feature exists, but if it did I would be very pleased indeed. Has anyone tackled this type of problem before? It's looking like I am going to wind up needed some type of extension method in the end...
Unless I'm missing something in your question, this is exactly what you're supposed to be doing. I'm pretty sure every exception includes an overload that takes string message as a parameter. If you want to provide information above and beyond the "default" provided by .NET, you need to set the specific message.
You seem to be doing this the right way to begin with. I would however change the way you check for exceptions:
public string GetMetadata(string metaDataKey)
{
try
{
string val = _Metadata[metaDataKey].TrimEnd();
return val;
}
catch (KeyNotFoundException ex)
{
// or your own custom MetaDataNotFoundException or some such, ie:
// throw new MetaDataNotFoundException(metaDatakey);
throw new KeyNotFoundException(string.Format("There is no metadata that contains the key '{0}'!", metaDataKey));
}
}
Just inherit from the KeyNotFoundException class and override the Message property to generate a more meaningful message and then use your own exception class with a proper constructor. This is exactly what inheritance was meant for, adding value. i.e.
throw new MetaDataKeyNotFoundException(string metaDataKey);
The Exception class already supports adding custom user data associated to a specific occurrence or scenario in which the error occurred through the use of the property Exception.Data.
From MSDN entry for that property, emphasis is mine:
Gets a collection of key/value pairs that provide additional user-defined information about the exception.
I know that you were looking to override the Message property, but using Data you can achieve the same by just making sure that the exception handler knows how to deal with this additional data.
An exception is an object. As with most objects, you can't control how the creator creates the object, whether or not the creator is the .NET Framework.
How would you even tell the .NET Framework what message to create under which circumstances? You would want one message on a KeyNotFoundException in the case you posted, and another message in a different circumstance. How would you distinguish the two situations?
KeyNotFoundException.SetMessage("this
is my custom message!");
There is no such feature (apart from messing with internals or resources maybe). But how should it work anyway. You would be changing the message for every piece of code that uses the exception - to some of which your new message would make no sense at all.
Consider some arbitrary use of the Dictionary class, or even some totally different code, that follows the "best practice" of reusing existing exception types, all of them would suddenly use your (very much) custom error message.
Here is a solution that I came up with, but I would like to note that it is more of a patch than anything. It does work, but probably isn't suitable for all applications. I couldn't even think of a good name for it either.
public class ContextDictionary<TKey, TValue> : Dictionary<TKey, TValue>
{
public TValue this[TKey key, string context]
{
get
{
if (!this.ContainsKey(key))
{
throw new KeyNotFoundException(string.Format("There is no {0} that contains the key '{1}'!", context, key));
}
return this[key];
}
set { this[key] = value; }
}
}
So now I can say something like this, and get the more descriptive exception message that I really want.
var _MetaData = new ContextDictionary<string,string>();
string val = _Metadata[metaDataKey, "metadata"].TrimEnd();
Related
I just want to know what do you think about where to define, throw and catch Exception and see if there is a consensus about does consideration.
Let me state an example to base on.
Let say I have solution and in that solution I have 2 projects: DomainProject and ControllerProject.
In the DomainProject I have a repository for doing some query for instance in the RepositoryClass I have the method:
GetObjectById(int id) { ... }
And I have some Exception define in this project like ObjectNotFoundException.
In the ControllerProject I want to query my repository so I do something that would look like:
MyObject obj = repo.GetObjectById(11);
Now the question is who should take care of checking if the id does really exist. If you choose that the ControllerProject should check for the existence of the id you can end up with some code like this:
MyObject obj = repo.GetObjectById(11);
if (obj == null) {throw new ObjectNotFoundException();}
But the down side of that is that it tend to be duplicate all over the place where GetObjectById is used. Of course there is some situation where you won't care if you get a null value so it somehow legitimate to not throw the exception in the DomainProject directly. But I first don't like to duplicate the if test and second, more related to my question, I don't like to use an exception define outside the current project.
I have the feeling that an Exceptions should only be throw in the project where it is define and other projects should only be catching them.
So back to my example, how would I solve this situation. Well a simple idea is to define 2 method in my domain project. One that throw an exception and one that does not. The only thing that I am not sure of is which naming convention I have to used: GetObjectByIdThrowsIfNotFound() and GetObjectById(). Or may be I can just add an optional parameter GetObjectById(int id, bool isExceptionThrow = true).
What do you think about the Exception?
Thanks
I think it is great that you are being thoughtful about how to let your design properly communicate intent. I agree with your misgivings: the only layer throwing the exception should be the layer that defined the exception.
That said, you only need an exception-throwing variant if a null return value is ambiguous, if it is valid to associate a key with a null. If not (and this should be noted in your XML comments!), then a null return always means the same thing (value not found) and you can save yourself the code and processing overhead of an exception in you Domain layer. If 'value not found' is a truly exceptional event in your Controller layer, define and throw the exception there.
If a 'stored null' is valid, I use the semantic pattern established by IDictionary<T>: bool TryGetObjectById(int id, out object value), and I only include an exception-throwing GetObjectById(int key) variant if a key-not-found is truly exceptional, and I want to save the keystrokes involved in calling the Try... variant down the road.
There are two patterns I see often:
1) The repository itself should throw the exception, and your calling method should wrap in a try / catch block if you want to handle the failure to get the item. I think this pattern would be the prime candidate for your application since it's the responsibility of the caller to deal with exceptions. I would assume that your repository doesnt catch SqlException or whatever persistence layer exceptions get thrown right? If so, then you should let the repository throw the exception and let it bubble up the stack.
If not....
2) You expose the object wrapped in a container to tell you of failure or success:
public class RepositoryItemContainer<DataType>
{
public DataType Object { get; set; }
public bool WasFound { get; set; }
}
Then, instead of just returning the value, you return this wrapper and the code can then decide what it wants to do:
var repoItem = _repo.GetObjectById(11);
if(repoItem.WasFound)
var item = repoItem.Object;
else
throw new ApplicationSpecificException("Wasnt found yo!")
Here are just a couple of considerations:
The Exceptions are for exceptional situations. So if you think that absence of the object in DB is an exceptional situation, I would say go in the way you implement it now.
If it's not exceptional case, implement a method in a way that it does not raise and Exception, but returns null, in case the id we query for is missed, naturally. Seems natural and keeps expected behaviour for a developer that will consume the repo class you implemented.
You can add kind of ContainsId(long id) method, that first checks for presence of requiered id in DB. Could be a good choice too, but I personally would prefer second point.
Hope this helps.
What are the pros and cons of implementing a custom exception as follows:
Create an enum which represents error messages in its descriptions:
public class Enums
{
public enum Errors
{
[Description("This is a test exception")]
TestError,
...
}
}
Create a custom exception class:
public class CustomException : ApplicationException
{
protected Enums.Errors _customError;
public CustomException(Enums.Errors customError)
{
this._customError = customError;
}
public override string Message
{
get
{
return this._customError!= Enums.Errors.Base ? this.customError.GetDescription() : base.Message;
}
}
}
The GetDescription method is an enum extension method which gets the enum description using reflection. This way, I can throw exception like:
throw new customException(enums.Errors.TestError);
And show it to the user in catch block like:
Console.WriteLn(ex.Message);
I've seen this approach recommended by an MVP. What are the benefits of this approach over the followings:
Using generic exception: throw new Exception("Error Message");.
Using Custom Exception: Define custom exceptions for any situation. e.g. (WebServiceException class, AuthenticationException class, etc.)
Here's the link to the recommendation by the MVP.
Thank you.
Personally, i don't think it's a good idea.
You should always throw as specific exceptions as possible. The same goes for catching.
It's easy to decide if we want to catch a WebServiceException or AuthenticationException, but with your Enum-example, we have to parse a string to decide if we want to catch it or not. What happens if this message changes?
I don't think it has any benefits at all. For each error type, you have to create a new Enum member. Why not create a new class instead?
The major advantage of custom exceptions is the language support for differentiation between different exception types. For example
try
{
SomeFunc()
}
catch( CustomException EX)
{
//This is my error that I know how to fix
FixThis()
DoSomeAwesomeStuff()
}
catch( Exception exa)
{
//Somthing else is wrong
WeepLikeBaby();
}
If I use the message Property
try
{
SomeFunc()
}
catch( Exception exa)
{
if(exa.Message == "ErrType 1")
{
DoStuff;
}
if(exa.Message == "ErrType 2")
{
Die();
}
}
Utilizing The Base enum example can still retain this capability. However you give yourself one place to define your messages, but that is solved in a variety of different ways by applications. The enum example would make creating localized messages pretty simple as It will give you A way to define your message strings independently.
Another Advantage is that you can add Cusotm data that makes sense in you application. Say for example you have a customer information system, and the customer ID is almost always going to be important. If you utilize the message property only, every handler will have to know how to parse out that information if needed.
public class MyCustomeEx : Exception
{
int CustID { get; set; }
}
public void Fail()
{
//Awww Customer error
throw new MyCustomeEx () {CustID = 123}
}
Option 1 I would not recommend. You should not be throwing System.Exception at all. You should always throw the most specific exception available for your situation in order to have reasonably structured exception handling in your code.
The major drawback I see in your proposed method (Errors enum) is that there is no way you can decide if you want to handle or not the exception without catching it first. With custom exceptions you can make that decision beforehand.
Please see my (accepted) answer at the following similar Stack Overflow question: Custom exception vs built in exception with very descriptive message. It should prove helpful in providing arguments against frivilous custom exceptions.
The link to the MVP's recommendation was shared in comments.
After looking at the code and the question I think the reason for this is to limit the possible messages in the exception. And maybe help with localizing exception texts, but then there's extra work to do in this example. Anyways, such a method shouldn't be used for creating "Exception sub-types" that are processed differently.
Once I read an MSDN article that encouraged the following programming paradigm (its not 100% true... see edit):
public class MyClass
{
public void Method1()
{
NewCustomException();
}
public void Method2()
{
NewCustomException();
}
void NewCustomException()
{
throw new CustomException("Exception message");
}
}
Do you think this paradigm makes sense? Wouldn't it be enough to store the exception message in a static const field and then pass it to the exception's constructor, instead of encapsulating the whole exception throw?
EDIT:
Use exception builder methods. It is
common for a class to throw the same
exception from different places in its
implementation. To avoid excessive
code, use helper methods that create
the exception and return it.
I just noticed (see citation), that the article tells to return an exception:
public class MyClass
{
public void Method1()
{
throw NewCustomException();
}
public void Method2()
{
throw NewCustomException();
}
CustomException NewCustomException()
{
return new CustomException("Exception message");
}
}
What do you think about this?
My understanding is that passing an exception instance around is a faux pas if for no other reason than you lose the stack trace associated with the exception. Calling another method would change the stack trace and thereby make it effectively useless. I'd recommend at a minimum getting the stack trace off the exception and passing it as an argument to some helper if that's the road you're going to go down.
That's a refactor too far in my book. You have to go back up a line in the stack trace to see exactly where the problem occured. If your custom exception is always using the same message, put it in the CustomException class. If it's only the same within the code you've quoted, then yes, put it in a const field (you can't have static const - it's implicitly static).
Another problem you get doing that is that there will be lots of places where you wont even be able to throw an exception because the compiler wont allow it. Consider these two methods added to your class:
public string GetFoo1(bool bar)
{
if (bar)
return "";
else
NewCustomException();
}
public string GetFoo2(bool bar)
{
if (bar)
return "";
else
throw new CustomException("Exception message");
}
GetFoo1 will not compile while GetFoo2 will.
I would have a method that builds an Exception, rather than one that throws it. As in the sample below. I seem to remember seeing a Microsoft guideline that recommended this, but I can't remember where.
With this technique, if you want to change the exception type for any reason, you only need to do so in one place (e.g. a change from ConfigurationException to ConfigurationErrorsException when upgrading from .NET 1.x to .NET 2.0).
Also you respect the DRY principle by having a single copy of the code that builds the exception with its message and any other data included in the exception.
You obviously wouldn't do this in trivial cases (e.g. you wouldn't replace throw new ArgumentNullException("myParamName") by throw BuildArgumentNullException("myParamName"))
private static Exception BuildSomeException(... parameters with info to include in the exception ...)
{
string message = String.Format(...);
return new SomeException(message, ...);
}
...
throw BuildSomeException(...);
I don't see the point of making a method that simply throws an exception. But, I do think trowing custom exceptions has value. If all of the exceptions you throw are children of a custom exception, it allows you to quickly see if the thrown exception is one you are accounting for or something you have not handled yet. Also, you can then catch MyBaseException and it is not as bad as catching Exception.
It is handy to do this if you don't know how you plan to handle exceptions, exactly. Do you want to just throw it? Or perhaps later you are going to log the exception somewhere then throw it? Or maybe pass some arguments (i.e. method name, etc.) that get bundled in with the exception?
In this case, creating a separate method that handles the exception situation is convenient when you want to change it.
I don't usually bother with this - instead, just figure out upfront how you are going to handle exceptions (i.e. what string information you are going to putin the message).
I generally prefer to store exception messages as resources. That serves several purposes:
If the requirement comes down to localize exception messages, it's a no-brainer.
Exception messages tend to be more standardized across developers since it's extra work to create a new, but only slightly different message.
If you ensure that messages are referenced by an identifier, and include the identifier with the exception when it's thrown, then tracing a message to the code that threw it is easier.
Downside is it does require (just) slightly more effort up front than hard-coding the messages.
Consider the following method signature:
public static bool TryGetPolls(out List<Poll> polls, out string errorMessage)
This method performs the following:
accesses the database to generate a list of Poll objects.
returns true if it was success and errorMessage will be an empty string
returns false if it was not successful and errorMessage will contain an exception message.
Is this good style?
Update:
Lets say i do use the following method signature:
public static List<Poll> GetPolls()
and in that method, it doesn't catch any exceptions (so i depend the caller to catch exceptions). How do i dispose and close all the objects that is in the scope of that method? As soon as an exception is thrown, the code that closes and disposes objects in the method is no longer reachable.
That method is trying to do three different things:
Retrieve and return a list of polls
Return a boolean value indicating success
Return an error message
That's pretty messy from a design standpoint.
A better approach would be to declare simply:
public static List<Poll> GetPolls()
Then let this method throw an Exception if anything goes wrong.
This is definitely not an idiomatic way of writing C#, which would also mean that it probably isn't a good style either.
When you have a TryGetPolls method then it means you want the results if the operation succeeds, and if it doesn't then you don't care why it doesn't succeed.
When you have simply a GetPolls method then it means you always want the results, and if it doesn't succeed then you want to know why in the form of an Exception.
Mixing the two is somewhere in between, which will be unusual for most people. So I would say either don't return the error message, or throw an Exception on failure, but don't use this odd hybrid approach.
So your method signatures should probably be either:
IList<Poll> GetPolls();
or
bool TryGetPolls(out IList<Poll> polls);
(Note that I'm returning an IList<Poll> rather than a List<Poll> in either case too, as it's also good practice to program to an abstraction rather than an implementation.)
I believe
public static bool TryGetPolls(out List<Poll> polls)
would be more appropriate. If the method is a TryGet then my initial assumption would be there is reason to expect it to fail, and onus is on the caller to determine what to do next. If they caller is not handling the error, or wants error information, I would expect them to call a corresponding Get method.
As a general rule, I would say no.
The reason I say no is actually not because you're performing a TryGetX and returning a bool with an out parameter. I think it's bad style because you're also returning an error string.
The Try should only ignore one specific, commonly-encountered error. Other problems may still throw an exception with the appropriate exception message. Remember that the goal of a Try method like this is to avoid the overhead of a thrown exception when you expect a particular, single sort of failure to happen more frequently than not.
Instead, what you're looking for is a pair of methods:
public static bool TryGetPolls( out List<Poll> polls );
public static List<Poll> GetPolls();
This way the user can do what's appropriate and GetPolls can be implemented in terms of TryGetPolls. I'm assuming that your staticness makes sense in context.
Consider returning:
an empty collection
null
Multiple out parameters, to me, is a code smell. The method should do ONE THING only.
Consider raising and handling error messages with:
throw new Exception("Something bad happened");
//OR
throw new SomethingBadHappenedException();
No, from my point of view this is very bad style. I would write it like this:
public static List<Poll> GetPolls();
If the call fails, throw an exception and put the error message in the exception. That's what exceptions are for and your code will become much cleaner, more readable and easier to maintain.
Not really - I can see a number of problems with this.
First of all, the method sounds like you'd normally expect it to succeed; errors (cannot connect to database, cannot access the polls table etc) would be rare. In this case, it is much more reasonable to use exceptions to report errors. The Try... pattern is for cases where you often expect the call to "fail" - e.g. when parsing a string to an integer, chances are good that the string is user input that may be invalid, so you need to have a fast way to handle this - hence TryParse. This isn't the case here.
Second, you report errors as a bool value indicating presence or absence of error, and a string message. How would the caller distinguish between various errors then? He certainly can't match on error message text - that is an implementation detail that is subject to change, and can be localized. And there might be a world of difference between something like "Cannot connect to database" (maybe just open the database connection settings dialog in this case and let the user edit it?) and "Connected to database, but it says 'Access Denied'". Your API gives no good way to distinguish between those.
To sum it up: use exceptions rather than bool + out string to report messages. Once you do it, you can just use List<Poll> as a return value, with no need for out argument. And, of course, rename the method to GetPolls, since Try... is reserved for bool+out pattern.
The guidelines say to try to avoid ref and out parameters if they are not absolutely required, because they make the API harder to use (no more chaining of methods, the developer has to declare all the variables before calling the method)
Also returning error codes or messages is not a best practice, the best practice is to use exceptions and exception handling for error reporting, else errors become to easy to ignore and there's more work passing the error info around, while at the same time losing valuable information like stacktrace or inner exceptions.
A better way to declare the method is like this.
public static List<Poll> GetPolls() ...
and for error reporting use exception handling
try
{
var pols = GetPols();
...
} catch (DbException ex) {
... // handle exception providing info to the user or logging it.
}
It depends on what the error message is. For instance, if processing couldn't continue because the database connection wasn't available, etc., then you should throw an exception as other people have mentioned.
However, it may be that you just want to return "meta" information about the attempt, in which case you just need a way to return more than one piece of information from a single method call. In that case, I suggest making a PollResponse class that contains two properties: List < Poll > Polls, and string ErrorMessage. Then have your method return a PollResponse object:
class PollResponse
{
public List<Poll> Polls { get; }
public string MetaInformation { get; }
}
Depends on if an error is a common occurance or if it us truly an exception.
If errors are gunuinely rare and bad then you might want to consider having the method just return the list of polls and throw an exception if an error occurs.
If an error is something that is realtively common part of normal operations, as like an error coverting a string to an integer in the int.TryParse method, the method you created would be more appropriate.
I'm guessing the former is probably the best case for you.
It depends on how frequently the method will fail. In general, errors in .Net should be communicated with an Exception. The case where that rule doesn't hold is when the error condidition is frequent, and the performance impact of throwing and exception is too high.
For Database type work I think an Exception is best.
I'd restate it like this.
public static List<Poll> GetPolls()
{
...
}
It should probably be throwing an exception (the errorMessage) if it fails to retrieve the polls, plus this allows for method chaining which is less cumbersome than dealing with out parameters.
If you run FxCop, you'll want to change List to IList to keep it happy.
I think its fine. I would prefer though:
enum FailureReasons {}
public static IEnumerable<Poll> TryGetPolls(out FailureReasons reason)
So the error strings don't live in the data-access code...
C# Methods should really only do one thing. You're trying to do three things with that method. I would do as others have suggested and throw an exception if there is an error. Another option would be to create extension methods for your List object.
e.g. in a public static class:
public static List<Poll> Fill( this List<Poll> polls) {
// code to retrieve polls
}
Then, to call this, you would do something like:
List<Poll> polls = new List<Poll>().Fill();
if(polls != null)
{
// no errors occur
}
edit: i just made this up. you may or may not need the new operator in List<Poll>().Fill()
Please state your assumptions, constraints, desires/goals, and reasoning; we're having to guess and/or read your mind to know what your intentions are.
assuming that you want your function to
create the polls list object
suppress all exceptions
indicate success with a boolean
and provide an optional error message on failure
then the above signature is fine (though swallowing all possible exceptions is not a good practice).
As a general coding style, it has some potential problems, as others have mentioned.
There is also this pattern, as seen in many Win32 functions.
public static bool GetPolls(out List<Poll> polls)
if(!PollStuff.GetPolls(out myPolls))
string errorMessage = PollStuff.GetLastError();
But IMO it's horrible.
I would go for something exception based unless this method has to run 65times per second in a 3d game physics engine or someting.
Did I miss something here? The question asker seems to want to know how to clean up resources if the method fails.
public static IList<Poll> GetPolls()
{
try
{
}
finally
{
// check that the connection happened before exception was thrown
// dispose if necessary
// the exception will still be presented to the caller
// and the program has been set back into a stable state
}
}
On a design side note, I'd consider pushing this method into a repository class so you have some sort of context with which to understand the method. The entire application, presumably, is not responsible for storing and getting Polls: that should be the responsibility of a data store.
When you try to access a key which isn't in a Dictionary (for example), here's the stack trace you get :
at System.ThrowHelper.ThrowKeyNotFoundException()
at System.Collections.Generic.Dictionary`2.get_Item(TKey key)
.... .... (my own code stack trace)
Like most people probably do, I log this errors when they occur, and try to figure out what happened.
The two key informations I want are where did this occur (the stacktrace is very helpful for that), and the key which caused the exception, which doesn't appear anywhere.
Either I didn't look properly (the KeyNotFoundException class contains a "Data" member, which is always empty, and the "Message" field" doesn't contain the key value), or it wasn't included in the framework at all.
I can't imagine nobody in the .net BCL team thought this would be an useful feature to have. I'm curious to know why they didn't include it. Are there some good reasons not to?
How do you deal with those exceptions ? The only alternative I can think of is to use a custom extension method on Dictionary which would wrap the call, catch the exception, and rethrow it with additional information regarding the key, but that wouldn't help for code I don't own, and it feel broken to change such a "base" functionality.
What do you think ?
I'm aware of this question, regarding the general fact that one cannot access the arguments of the method which raised an exception. My question is specifically related to the KeyNotFoundException.
Edit : I'm aware of the TryGetValue pattern, I do that all the time when I expect that my collection may not contain the key. But when it should contain it, I don't test, because I prefer my program to fail with an exception so that I know something unexpected happened before (ie at the time when the key should have been inserted)
I could wrap a try/catch/log error/rethrow around all my dictionary access, but this would lead to difficult-to-read code, cluterred with all my exception handling/logging stuff.
Why do you rely on (slow) exceptions? Just verify whether the key exists with ContainsKey or TryGetValue?
I don't know the reason why the exception doesn't contain the error-causing field (maybe because it should be ungeneric) but just wrap it if you think you'll need it.
class ParameterizedKeyNotFoundException<T> : KeyNotFoundException {
public T InvalidKey { get; private set; }
public ParameterizedKeyNotFoundException(T InvalidKey) {
this.InvalidKey = InvalidKey;
}
}
static class Program {
static TValue Get<TKey, TValue>(this IDictionary<TKey, TValue> Dict, TKey Key) {
TValue res;
if (Dict.TryGetValue(Key, out res))
return res;
throw new ParameterizedKeyNotFoundException<TKey>(Key);
}
static void Main(string[] args) {
var x = new Dictionary<string, int>();
x.Add("foo", 42);
try {
Console.WriteLine(x.Get("foo"));
Console.WriteLine(x.Get("bar"));
}
catch (ParameterizedKeyNotFoundException<string> e) {
Console.WriteLine("Invalid key: {0}", e.InvalidKey);
}
Console.ReadKey();
}
}
You could use the ContainsKey or TryGetValue method instead to verify if the dictionary contains the key.
As darin pointed out, you should really be account for this in your code, but if for whatever reason, that's not possible, you could do the following.
public object GetObjectFromDictionary(string key)
{
try
{
return MyDictionary[key];
}
catch (KeyNotFoundException kex)
{
throw new WrappedException("Failed To Find Key: " + key, kex);
}
}
I can't really enlight you on why the didn't include the key in the exception. As darin stated, you should be always using TryGetValue - it makes the code easier to read, to maintain and you won't get a KeyNotFoundException (and, while your at it, always use TryParse instead of Parse, for int, double, DateTime, whatever, for the same reason).
However, once you got them:
How do you deal with those exceptions ?
Since you know where the exception is thrown, if the code is not utterly complex, this allows you to reproduce the bug (enable "Break on thrown exception", or whatever it's called in the English version, in the Debugging->Exceptions dialog for this exception to break in that very moment), and I usually find out what the reason is in a few minutes. The debugger tells you what the key is in that case, and then it's your work to find out why that's the key (or why the key isn't in the dictionary) anyway, even if you got the key name through a bug report. Unless you have some kind of god dictionary where absolutely everything is in, it should be rather easy to figure out where the problem is.
There shouldn't be any unhandled exceptions left in the code, so it should be a rare case to encounter such a thing, and then it's ok for me to investigate a little further. In other words, I never felt the need to get the key from a bug report.
Of course, well, if you can't reproduce the bug, this won't help you - I then typically add logging code to the failing area and hand that version out to the customer that encountered the bug (if it's more than one customer, it's typically possible to reproduce the bug with the customer's data).
But then, I'm developing software for other companies and not shrink-wrap software, so things might be different for you regarding the time you can spend with the customer.