25

I am constructing a list of strings and then want to throw an exception and let the UI handle the list and create the error message for the user.

Is there a way to do that?

Paul
  • 247
  • 1
  • 4
Pacman
  • 2,183
  • 6
  • 39
  • 70

2 Answers2

45

Exceptions contains Data property (which is a dictionary). It can be used to pass additional information:

try
{
    // throw new Exception
}
catch(Exception e)
{
    // whatever
    e.Data["SomeData"] = new List<string>();
}
Zbigniew
  • 27,184
  • 6
  • 59
  • 66
  • 2
    And if you need to include the object in a throw statement (in case you want it to bubble up potentially several levels), you can just do `var e = new Exception("some error") { Data = { {"obj1", obj1}, {"obj2", obj2} } } }` and then `throw e` – jbyrd May 09 '18 at 13:25
36

You can use the Exception.Data property to pass arbitrary data but a better (cleaner) solution would be to create your own custom exception class derived from Exception and add whatever properties you need to it.

Sample code:

public class MyException: Exception
{
    public List<String> MyStrings { get; private set; }

    public MyException(List<String> myStrings)
    {
        this.MyStrings = myStrings;
    }
}
Z .
  • 12,657
  • 1
  • 31
  • 56