سؤال

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.

هل كانت مفيدة؟

المحلول 2

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.

نصائح أخرى

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

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

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top