Possible Duplicate:
Catching specific vs. generic exceptions in c#
Here’s an example method
private static void outputDictionaryContentsByDescending(Dictionary<string, int> list)
{
try
{
//Outputs entire list in descending order
foreach (KeyValuePair<string, int> pair in list.OrderByDescending(key => key.Value))
{
Console.WriteLine("{0}, {1}", pair.Key, pair.Value);
}
}
catch (Exception e)
{
MessageBox.Show(e.Message, "Error detected", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
I would like to know what exception clause to use apart from just Exception and if there is an advantage in using more specific catch clauses.
Edit: O.k thanks everyone
The only potential cause for an exception that I see in your example is if
listis null.OrderByDescending()should return an emptyIEnumerable<>rather than a null reference.If I read that correctly, it might make more sense to catch
NullReferenceException:However, this really depends on the needs of your application. If your intention is just to alert the user or to log all exceptions, catching the
Exceptionclass is fine. If you need special handling for different types of exceptions – such as sending an email alert instead of just logging the message – then it makes sense to use specific exception types: