Ala*_*ain 12 c# exception-handling
我有尝试类型转换的代码.如果失败,我想尝试别的东西,如果失败,则重新抛出第一次转换尝试的原始异常.问题是,我知道要重新抛出的唯一方法就是throw;"坐在拦截块的末端".当我只希望从另一个catch块中发生重新抛出时会发生什么?
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; }
}
Run Code Online (Sandbox Code Playgroud)
如您所见,我必须使用' throw e;',它会重置调用堆栈.
到目前为止我唯一的解决方法是(imo)粗略:
bool handled = true;
...
catch { handled = false; }
if( !handled ) throw;
Run Code Online (Sandbox Code Playgroud)
无法从catch块catch内的外部块重新抛出异常inner.实现此模式的最佳方法是注意内部操作是否成功
catch (InvalidCastException e) {
bool threw = false;
try {
...
} catch {
threw = true;
}
if (threw) {
throw;
}
}
Run Code Online (Sandbox Code Playgroud)