Dimitri
Dimitri

Reputation: 2858

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

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.

Upvotes: 8

Views: 4027

Answers (2)

Barrie Sargent
Barrie Sargent

Reputation: 11

I had a similar need, but my base constructor initializes some read-only properties based on a parameter passed in from the derived class, so the above solution wouldn't work for me. What I did was add a read-only Exception property to the base class that gets set in the catch clause within the constructor, and which the derived class can then check in its own constructor and handle appropriately.

class Base
{
    public Base(string parameter)
    {
        try
        {
            // do something with parameter
        }
        catch (Exception exception)
        {
            ExceptionProperty = exception;
        }
    }

    public Exception ExceptionProperty  { get; }
}

class Derived : Base("parameter")
{
    if (ExceptionProperty != null)
    {
        // handle the exception
    }
}

Upvotes: 1

dtb
dtb

Reputation: 217303

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();

Upvotes: 13

Related Questions