C# Can';t捕获派生类中引发的异常
为什么基类的try-catch不捕获派生类中抛出的异常? 我错过什么了吗 基类:C# Can';t捕获派生类中引发的异常,c#,exception-handling,derived-class,base-class,C#,Exception Handling,Derived Class,Base Class,为什么基类的try-catch不捕获派生类中抛出的异常? 我错过什么了吗 基类: public class UmBase { protected Thread ThisThread; protected UmBase(int cycleMs, UpdateManager updateManager, string loggerFilename, string loggerFolder = "UpdateManager") {
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);
}
}
}
我在这里读过,找不到我的错误。当你覆盖一个方法时,你实际上会替换整个方法,就派生类的实例而言
除非从被重写的方法显式调用继承的方法,否则它不是派生类逻辑的一部分。当您
重写一个方法时,实际上就派生类的实例而言,您会整体替换整个方法
除非从重写的方法显式调用继承的方法,否则它不是派生类逻辑的一部分。Try/Catch将只捕获Try块中抛出的异常。它包括由try块内调用的其他方法引发的任何异常。您是否已将异常配置为仅在未处理时中断,或在抛出时也中断
另一种可能是在构建对象时引发异常,因为ReadParams构造函数在没有try/catch的情况下调用迭代()
i、 e
Try/Catch只捕获Try块中抛出的异常。它包括由try块内调用的其他方法引发的任何异常。您是否已将异常配置为仅在未处理时中断,或在抛出时也中断
另一种可能是在构建对象时引发异常,因为ReadParams构造函数在没有try/catch的情况下调用迭代()
i、 e
如果我读对了,顺序是:
读取参数
伞形花序
ReadParams迭代
ReadParams迭代抛出新异常(“Oops!”,异常)代码>
崩溃。。。因为ReadParams中没有try-catch
如果我读对了,顺序是:
读取参数
伞形花序
ReadParams迭代
ReadParams迭代抛出新异常(“Oops!”,异常)代码>
崩溃。。。因为ReadParams中没有try-catch
我也面临同样的问题。我注意到一件事,但不确定原因。
当您私下继承基类时,其catch块不会捕获派生类的异常。
公开继承基类并尝试一下。我也遇到了同样的问题。我注意到一件事,但不确定原因。
当您私下继承基类时,其catch块不会捕获派生类的异常。
公开继承基类并尝试一下。可能重复的可能重复的
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);
}
};
}