如何从嵌套的try-catch块中重新抛出先前的异常? (C#) [英] How to rethrow a prior exception from inside a nested try-catch block? (C#)
问题描述
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屋!