Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to catch exception thrown from base class constructor inside derived class constructor

Tags:

c#

inheritance

Suppose I have a following code

class Base
{
    public Base()
    {
        throw new SomeKindOfException();
    }  
}

class Derived : Base
{

}

and suppose I instantiate Derived class.

Derived d = new Derived();

In order for Derived class to be instantiated the Base class should be instantiated firstly right ? so is there any theoretical or practical way to catch an exception thrown from base class constructor in derived class constructor. I suppose there is not, but I'm just curious.

like image 668
Dimitri Avatar asked Sep 13 '13 21:09

Dimitri


1 Answers

The constructor of Base is always executed before any code in the constructor of Derived, so no. (If you don't explicitly define a constructor in Derived, the C# compiler creates a constructor public Derived() : base() { } for you.) This is to prevent that you don't accidentally use an object that has not been fully instantiated yet.

What you can do is initialize part of the object in a separate method:

class Base
{
    public virtual void Initialize()
    {
        throw new SomeKindOfException();
    }  
}

class Derived : Base
{
    public override void Initialize()
    {
        try
        {
            base.Initialize();
        }
        catch (SomeKindOfException)
        {
            ...
        }
    }
}
var obj = new Derived();
obj.Initialize();
like image 106
dtb Avatar answered Sep 28 '22 12:09

dtb