1

I'm playing around with improving my error handling, and also learning nLog. I'd like to be able to cause some "real" errors to test what my error handling is doing. Are there any that are easy to intentionally cause that will have inner exceptions in them, especially multiple levels? For example, I've already done stuff like divide by 0 and SQL queries to non-existent tables, but neither of these has an inner exception.

techturtle
  • 2,519
  • 5
  • 28
  • 54

3 Answers3

4

You can create your own nested exceptions to the nth degree.

throw new Exception("1", new Exception("2", new Exception("3")));

enter image description here

George
  • 41
  • 4
3

You could use Task.Run(() => throw new Exception()); for example. This will throw an AggregateException which will contain the exception as an inner exception. Invoking things that throw exceptions via reflection will also cause a TargetInvocationException to be thrown containing the actual exception as an inner exception.

Using the XmlSerializer to deserialize an invalid XML file usally produces a more deeply nested error hierarchy if I recall correctly.

For example the following program will throw an exception three "levels" deep:

public class MyClass
{
   [XmlElement("Element")]
   int Element { get; set; }

}
class Program
{
   static void Main(string[] args)
   {
      string xml = "<Element>String</Element>";
      XmlSerializer serializer = new XmlSerializer(typeof(MyClass));
      serializer.Deserialize(new StringReader(xml));
   }
}

But by far the simplest solution of course is to throw your own nested exception.

DeCaf
  • 6,026
  • 1
  • 29
  • 51
  • Your code was easy to implement and worked well, though it only threw 2 exceptions deep for me. Still, that was all I really needed because I now have realistic exceptions to work with. Thanks! – techturtle May 21 '13 at 19:30
0

Search for "XAMLParseException" - cause some errors in WPF window constructor. You'll find lots of examples.

JeffRSon
  • 10,404
  • 4
  • 26
  • 51