When debugging your code, Exceptions can be very useful. Exceptions can tell you a lot about what's happening when things go wrong. But sometimes we need more information about what's happening to be able to reproduce the error.
Take this code for an example:
public int ParseAge(string ageText)
{
var parts = ageText.Split(' ');
return int.Parse(parts[0]);
}
When trying to parse age from strings like "24 years old", this will work fine. But what happens if we input something that doesn't start with a number? We will then get a System.FormatException with the message 'Input string was not in a correct format.'.
What if you could add more data to that exception to help with debugging? You can!
The Exception class has a property called Data where you can add more information that relates to the Exception. You can do that by wrapping the code with a Try-Catch.
public static int ParseAge(string ageText)
{
try
{
var parts = ageText.Split(' ');
return int.Parse(parts[0]);
}
catch (Exception e)
{
e.Data.Add("AgeText", ageText);
throw;
}
}
To then display the data you loop thru the dictionary like this:
foreach (DictionaryEntry pair in ex.Data)
{
Console.WriteLine("{0} = {1}", pair.Key, pair.Value);
}
In a real application, this would of course be logged to a logging system like elasticsearch or seq.