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.
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.