CSharp · Console
using System;
using System.Reflection;
public class Program
{
public static void Main()
{
try
{
TestMethod1();
}
catch(Exception ex)
{
Console.WriteLine("Hey, Look! Exception {0}", ex);
}
try
{
TestMethod1();
}
catch(Exception ex)
{
Console.WriteLine("Hey, Look! Another Exception {0}", ex);
}
Console.WriteLine("Done");
}
public static void TestMethod1()
{
Test myObject = new Test();
Type testType = typeof(Test);
PropertyInfo prop = testType.GetProperty("TestProperty");
try
{
prop.SetValue(myObject, "cat");
}
catch (Exception ex) // The Exception IS caught.
{
Console.WriteLine("Caught Me!"); // This works
Console.WriteLine(ex.ToString()); // This works, displays the ArugmentException in console below
Console.WriteLine(ex.InnerException.Message); // This throws a NullReferenceException, and halts execution
Console.WriteLine("I'm never hit, previous line throws.");
}
}
public static void TestMethod2()
{
Test myObject = new Test();
Type testType = typeof(Test);
PropertyInfo prop = testType.GetProperty("AnotherTest");
try
{
prop.SetValue(myObject, "cat");
}
catch (Exception ex) // The Exception IS caught.
{
Console.WriteLine("Caught Me!"); // This works
Console.WriteLine(ex.ToString()); // This works, displays the ArugmentException in console below
Console.WriteLine(ex.InnerException.Message); // This throws a NullReferenceException, and halts execution
Console.WriteLine("I'm never hit, previous line throws.");
}
}
}
public class Test
{
public int TestProperty {get;set;}
private string anotherTest;
public string AnotherTest
{
get
{
return anotherTest;
}
set
{
throw new NotImplementedException();
}
}
}