【发布时间】:2017-01-05 00:44:29
【问题描述】:
允许使用自定义异常,可以像下面这样抛出异常。
try
{
int foo = int.Parse(token);
}
catch (FormatException ex)
{
//Assuming you added this constructor
throw new ParserException(
$"Failed to read {token} as number.",
FileName,
LineNumber,
ex);
}
但是在正常的 try catch 块中,它说,抛出异常将清除堆栈跟踪。
try
{
ForthCall();
}
catch (Exception ex)
{
throw ex;
}
那么在自定义异常中,如何在不清除堆栈跟踪的情况下使用 throw 异常?
【问题讨论】:
-
您将try block(FormatException)中的原始异常作为ParserException构造函数中的内部异常传递,因此您可以通过InnerException成员获取原始堆栈跟踪
-
内部异常怎么说?
-
根据您提到的链接中的代码。但是,此链接不提供您使用的构造函数的完整实现。只需修改这个 ParserException(string msg, Exception inner) : base(msg, inner) { }。因此,在捕获您的自定义 excexption 时,您可以将原始堆栈作为 YourCustomExceptionObject.InnerException.StackTrace
-
只说
throw而不是throw ex
标签: c# .net exception-handling