问题
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