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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With