在C#中,throw和throw ex都用于抛出异常,但它们在异常堆栈跟踪处理上有重要区别。
throw exresets the stack trace (so your errors would appear to originate fromHandleException) 重置堆栈跟踪throwdoes not - the original offender would be preserved. 保留堆栈跟踪
Throw
1 | { |
运行堆栈:
1 | An error occurred. |
保留了完整的堆栈跟踪
Throw preserves the stack trace. So lets say Source1 throws Error1 , its caught by Source2 and Source2 says throw then Source1 Error + Source2 Error will be available in the stack trace.
Throw ex
1 | { |
通常你会看到一个 build warning:
Rethrow to preserve stack details: https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca2200
运行堆栈:
1 | An error occurred. |
重置堆栈跟踪,丢失原始抛出位置信息
Throw ex does not preserve the stack trace. So all errors of Source1 will be wiped out and only Source2 error will sent to the client.
