Is it possible to throw an exception from the constructor of the base class inside the constructor of the derived class

Suppose I have the following code

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

and suppose I create a derived class.

 Derived d = new Derived(); 

To create an instance of the Derived class, must the Base class be emulated first correctly? so is there any theoretical or practical way to catch the exception thrown from the base class constructor into the derived class constructor. I suppose not, but I'm just curious.

+4
source share
2 answers

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

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(); 
+8
source

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

 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 } } 
0
source

Source: https://habr.com/ru/post/1502130/


All Articles