I was wondering how to catch an exception from a constructor in a derived class with C#. Something as such:
public class MyClassA
{
public MyClassA()
{
//Do the work
if (failed)
{
throw new Exception("My exception");
}
}
}
public class MyClassB : MyClassA
{
public MyClassB()
{
//How to catch exception from a constructor in MyClassA?
}
}
Do not even try to figure out how to do this. If the base class constructor is throwing an exception, it means the base class is in a bad state. If the base class is in a bad state, it means the derived class is in a bad state. The point of a constructor is to get an object into a useable state. It failed. Get out!
i would handle it like this i think
public class MyClassA
{
protected bool test;
public MyClassA()
{
//Do the work
if (true)
{
test = true;
return;
}
}
}
public class MyClassB : MyClassA
{
public MyClassB()
{
if (base.test)
{
//How to catch exception from a constructor in MyClassA?
}
}
}
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