如何从嵌套的try-catch块中重新抛出先前的异常? (C#) [英] How to rethrow a prior exception from inside a nested try-catch block? (C#)

查看:232
本文介绍了如何从嵌套的try-catch块中重新抛出先前的异常? (C#)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有代码尝试类型转换。如果它失败,我想尝试其他的东西,如果这也失败了,那么重新抛出第一次转换尝试的原始异常。问题在于,我知道要重新抛出的唯一方法就是将'$ $ $ $ $ $ $ $ $ $ $'$ $ $ $ $ $ $ $'当我只想在另一个catch块内发生反转时会发生什么?

  try 
{
valueFromData = Convert.ChangeType(valueFromData,pi.PropertyType);
}
catch(InvalidCastException e)
{
Debug.WriteLine(String.Concat(Info - Direct conversion failed。尝试使用String作为intermidiate类型转换)) );
try {valueFromData = Convert.ChangeType(valueFromData.ToString(),pi.PropertyType); }
catch {throw e; }
}

如上图所示,我必须使用'$ code> throw e; ',其中重置调用堆栈。



只有解决方法我已经到目前为止(imo)总计:

  bool processed = true; 
...
catch {handles = false; }
if(!handling)throw;


解决方案

没有办法从外部重新抛出异常catch $ / code> catch block 实现此模式的最佳方式是注意内部操作是否成功

  catch(InvalidCastException e){
bool threw = false;
try {
...
} catch {
threw = true;
}
if(threw){
throw;
}
}


I have code that attempts a type conversion. If it fails, I want to try something else, and if that also fails, then rethrow the original exception attempted by the first conversion. The problem is that the only way I know of to rethrow is to have 'throw;' sitting at the end of the catch block. What happens when I only want the rethrow to happen from within another catch block?

try 
{
    valueFromData = Convert.ChangeType(valueFromData, pi.PropertyType);
} 
catch(InvalidCastException e)
{
    Debug.WriteLine(String.Concat("Info - Direct conversion failed. Attempting to convert using String as an intermidiate type."));
    try { valueFromData = Convert.ChangeType(valueFromData.ToString(), pi.PropertyType); }
    catch { throw e; }
}

As you can see above, I have to use 'throw e;', which resets the call stack.

Only workaround I've though of so far is (imo) gross:

bool handled = true;
... 
catch { handled = false; }
if( !handled ) throw;

解决方案

There is no way to rethrow an exception from an outer catch block inside an inner catch block. The best way to achieve this pattern is to note whether or not the inner operation succeeded

catch (InvalidCastException e) {
  bool threw = false;
  try {
    ...
  } catch { 
    threw = true;
  }
  if (threw) {
    throw;
  }
}

这篇关于如何从嵌套的try-catch块中重新抛出先前的异常? (C#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆