大模型输出内容在深度和准确性上有欠缺,在专业领域应用时,生成信息未经严格验证,难以直接应用。
不要这样做,
try
{
...
}
catch(Exception ex)
{
throw ex;
}
你会失去堆栈跟踪信息...
要么做,
try { ... }
catch { throw; }
要么
try { ... }
catch (Exception ex)
{
throw new Exception("My Custom Error Message", ex);
}
你可能想要重新抛出的原因之一是,如果你正在处理不同的例外,例如
try
{
...
}
catch(SQLException sex)
{
//Do Custom Logging
//Don't throw exception - swallow it here
}
catch(OtherException oex)
{
//Do something else
throw new WrappedException("Other Exception occured");
}
catch
{
System.Diagnostics.Debug.WriteLine("Eeep! an error, not to worry, will be handled higher up the call stack");
throw; //Chuck everything else back up the stack
}
第一; 在文章中的代码的方式是邪恶的。 throw ex会将异常中的调用堆栈重置为这个throw语句所在的位置; 失去了关于实际创建异常的信息。
其次,如果你只是像这样捕获并重新抛出,我没有看到任何附加价值,上面的代码示例将是一样的好(或者,如果没有尝试捕获,甚至更好)。
但是,有些情况下您可能想要捕捉并重新抛出异常。 记录可能是其中之一:
try
{
// code that may throw exceptions
}
catch(Exception ex)
{
// add error logging here
throw;
}