[英]C# Throw being caught in last catch
I'm wondering if my understanding of Exception
is incorrect. 我想知道我对
Exception
理解是否不正确。 I have the following code: 我有以下代码:
try
{
// ... code calls a function which throws a UASException()
}
catch (UASException ex)
{
throw;
}
catch (Exception ex)
{
throw new UASException("An unknown error has occured", ex);
}
Now when I re-throw the UASException
it gets caught by the following Catch
, is this correct? 现在,当我重新抛出
UASException
它被以下Catch
,这是正确的吗? I thought it should return to the calling code with the re-thrown UASException
. 我认为它应该返回到重新抛出
UASException
的调用代码。
What could I be missing? 我能错过什么?
No it does not. 不,不是的。 Only one exception handler is picked (the one with the best matching exception type).
仅挑选一个异常处理程序(具有最佳匹配异常类型的异常处理程序)。 You could have easily tried, but...
你可以轻松尝试,但......
Example: The following code outputs "Catch 1" and not "Catch 2", which is what I'm saying. 示例:以下代码输出“Catch 1”而不是 “Catch 2”,这就是我所说的。 Only one
catch
is executed, no matter whether an exception occurs within the catch
block. 无论
catch
块中是否发生异常, catch
执行一个catch
。 To catch exceptions within a catch
block you need to nest catch
blocks. 要捕获
catch
块中的异常,您需要嵌套catch
块。
using System;
using System.Collections.Generic;
using System.Text;
namespace CSharp
{
public class Class1
{
public static void Main(string[] args)
{
try
{
throw new ArgumentException("BANG!");
}
catch (ArgumentException)
{
Console.WriteLine("Catch 1");
throw;
}
catch
{
Console.WriteLine("Catch 2");
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.