[英]Can't catch exception thrown in derived class
为什么基类的try-catch不能捕获派生类中引发的异常? 我错过了什么吗?
基类:
public class UmBase
{
protected Thread ThisThread;
protected UmBase(int cycleMs, UpdateManager updateManager,
string loggerFilename, string loggerFolder = "UpdateManager")
{
}
public void Start()
{
ThisThread = new Thread(Work);
ThisThread.Start();
}
public virtual void Iteration()
{
throw new Exception("Iteration Method should be overidden!");
}
public void Work()
{
while (IsProcessing)
{
try
{
Iteration();
}
catch (Exception exception)
{
Log.Error(exception.Message); //WANT TO HANDLE IT HERE
}
finally
{
Sleep(100);
}
};
}
}
派生类:
public class ReadParams : UmBase
{
public ReadParams(UpdateManager updateManager, int cycleMs = 60000)
: base(cycleMs, updateManager, "sss")
{
Iteration();
}
public override void Iteration()
{
try
{
DbParams.Set(); //EXCEPTION IS THROWN INSIDE
}
catch (Exception exception)
{
throw new Exception("Oops!", exception);
}
}
}
我在这里读过我们可以在C#的基类中捕获子类方法的异常吗? 找不到我的错误
Try / Catch将仅捕获在try块中引发的异常。 这包括在try块中调用的其他方法引发的任何异常。 您是否已将异常配置为仅在未处理或抛出时中断? 请参阅此处以了解如何配置异常中断
另一种可能性是在对象构造时抛出了异常,因为ReadParams构造函数在没有try / catch的情况下调用Iteration()。
即
public class ReadParams : UmBase
{
public ReadParams(UpdateManager updateManager, int cycleMs = 60000)
: base(cycleMs, updateManager, "sss")
{
Iteration();
}
public override void Iteration()
{
try
{
// If throw here (A)
DbParams.Set(); //EXCEPTION IS THROWN INSIDE
}
catch (Exception exception)
{
// I'll catch here (A) and then throw a new exception
throw new Exception("Oops!", exception);
}
}
}
public void Work()
{
while (IsProcessing)
{
try
{
// Exceptions thrown here including the one you
// threw in the method Iteration (B)
Iteration();
}
catch (Exception exception)
{
// Will be caught here (B)
Log.Error(exception.Message); //WANT TO HANDLE IT HERE
}
finally
{
Sleep(100);
}
};
}
如果我没看错,顺序是:
throw new Exception("Oops!", exception);
override
方法时,实际上就涉及派生类的实例而言,整个批发方法都将全部替换。
除非您从被重写的方法中显式调用继承的方法,否则它不是派生类逻辑的一部分。
我遇到了同样的问题。我注意到一件事,但不确定原因。 当u私有地继承基类时,其catch块不会捕获派生类的异常。 公开继承基类并进行尝试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.