gpt4 book ai didi

c# - .net 异常捕获 block

转载 作者:可可西里 更新时间:2023-11-01 08:56:52 24 4
gpt4 key购买 nike

以下 catch block 之间有什么区别?

try
{
...
}
catch
{
...
}

try
{
...
}
catch(Exception)
{
...
}

我意识到,在任何一种情况下,异常实例都不可用,但有什么我可以用一个实例做而另一个实例做不到的事情吗?

最佳答案

它们几乎相同。

来自 C# 语言规范,第 8.10 节:

Some programming languages may support exceptions that are not representable as an object derived from System.Exception, although such exceptions could never be generated by C# code. A general catch clause may be used to catch such exceptions. Thus, a general catch clause is semantically different from one that specifies the type System.Exception, in that the former may also catch exceptions from other languages.

请注意,虽然 C# 区分了两者,但它们实际上与 .NET 2.0 相同,如 this blog 所述:

Thanks to a recent change in the 2.0 CLR, if you had code that decided to throw, say, an int (System.Int32) somewhere, the CLR will now wrap it with a RuntimeWrappedException, and the compiler has been updated to give you that warning that the second clause above is now dead code

warning CS1058: A previous catch clause already catches all exceptions. All non-exceptions thrown will be wrapped in a System.Runtime.CompilerServices.RuntimeWrappedException

For how the CLR knows to do this action for your assembly, you'll notice the compiler now adds a RuntimeCompatibilityAttribute to your assemblies telling it to:
.custom instance void [mscorlib]System.Runtime.CompilerServices.RuntimeCompatibilityAttribute::.ctor() = {property bool 'WrapNonExceptionThrows' = bool(true)}

关于c# - .net 异常捕获 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5345436/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com