我想知道如何在派生类中使用C#赶上从构造函数的异常。有些事情是如此这样的:
公共类MyClassA
{
公共MyClassA()
{
//做的工作
如果(失败)
{
抛出新的异常(我的异常);
}
}
}
公共类MyClassB:MyClassA
{
公共MyClassB()
{
//如何从MyClassA构造赶上例外?
}
}
解决方案
甚至不要试图找出如何做到这一点。如果基类的构造函数抛出异常,这意味着基类是在一个糟糕的状态。如果基类是在一个糟糕的状态,这意味着派生类是在一个糟糕的状态。构造函数的关键是让一个对象进入可用状态。它失败了。滚出去!
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!
上一篇:屏幕尺寸和QUOT;与&QUOT差异;和"屏幕像素密度"在Android的?密度、像素、差异、屏幕
下一篇:Android的人脸检测MaxNumDetectedFaces的人、Android、MaxNumDetectedFaces