Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch exception from a constructor in a derived class with C#?

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?
    }
}
like image 999
c00000fd Avatar asked Dec 26 '22 01:12

c00000fd


2 Answers

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!

like image 110
jason Avatar answered May 14 '23 10:05

jason


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?
        }

    }
}
like image 45
Fredou Avatar answered May 14 '23 10:05

Fredou