c# Activator.CreateInstance cannot catch exception from instantiated class if I pass argument

811 Views Asked by At

I use Activator.CreateInstance to instantiate dynamic class, my class constructor generate Exception if issue appears.

When I use the parameterless constructor (Test 1), I can catch the exception launch by the instantiated class around the CreateInstance.

But, if I use constructor with argument, the exception is not catch by the try catch around the CreateInstance.

How I can catch this exception ?

using System;
using System.Text;

namespace ConsoleApplication1
{

    public abstract class Base
    {
        public Base()
        {
            throw new Exception(" -= TEST = Bad filename. =- ");
        }

        public Base( String filename)
        {
            throw new Exception(" -= TEST = Bad filename. =- ");
        }
    }

    public class Child : Base
    {
        public Child()
            : base()
        {

        }

        public Child(String filename)
            : base(filename)
        {

        }
    }

    class Program
    {
        static void Main(string[] args)
        {

            try
            {
                Base child = (Base)Activator.CreateInstance(typeof(Child));
            }

            catch (Exception e)
            {
                Console.WriteLine("Test 1 (no argument): Catch OK");        
                Console.WriteLine(e.ToString());
            }

            Console.WriteLine("Test 1: OK\n--------------------------");
            Console.ReadKey();

            try
            {
                Base child = (Base)Activator.CreateInstance(typeof(Child), "foo");
            }

            catch (Exception e)
            {
                Console.WriteLine("Test 2 (with argument): Catch OK");
                Console.WriteLine(e.ToString());
            }

            Console.WriteLine("The end");
            Console.ReadKey();
            }
    }
}
0

There are 0 best solutions below