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

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-14 01:16:57

问题


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

回答1:


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!




回答2:


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

    }
}



回答3:


1) A workaround: create a factory method in the derived:

class MyClassB : MyClassA
{
    public static MyClassB Create()
    {
        try
        {
            return new MyClassB();
        }
        catch
        {
            // try to handle
        }
    }
}

2) or create a similar in the base and don't throw in the constructor but in the method instead:

class MyClassA
{
    public static MyClassA Create()
    {
        MyClassA x = new MyClassA();
        if (x.Failed)
            throw new Exception();
        return x;
    }
}

3) or provide an overridable strategy to handle failed state:

class MyClassA
{
    public MyClassA
    {
        if (failed)
            OnFail();
    }

    protected virtual void OnFail()
    {
         throw new Exception();
    }
}

class MyClassB : MyClassA
{
    protected override void OnFail()
    {
        // don't throw
    }
}   



回答4:


I solve the same problem with static method:

public class PdfReaderExtended : PdfReader
{
    public PdfReaderExtended(string filename) : base(filename)
    {

    }

    public static PdfReaderExtended CreateInstance(string filename)
    {
        var name = Path.GetFileName(filename);
        try
        {
            return new PdfReaderExtended(filename);
        }
        catch (Exception ex)
        {
            throw new ClientException("Oops");
        }
    }
}


来源:https://stackoverflow.com/questions/17266105/how-to-catch-exception-from-a-constructor-in-a-derived-class-with-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!