在同一个catch块中捕获两个异常?
我有一种方法可以抛出两个不同的异常CommuncationException
和SystemException
。在两种情况下,我都执行相同的三行代码块。
try {
...
}
catch (CommunicationException ce) {
...
}
catch {SystemExcetion se) {
...
}
有可能这样做吗?
try {
...
}
catch (CommunicationException ce, SystemException se) {
...
}
这样,我就不必编写这么多代码。 我知道我可以将异常处理提取到私有方法,但是由于代码只有3行,因此方法定义将比主体本身花费更多的代码。
RoflcoptrException asked 2020-08-12T02:58:32Z
7个解决方案
151 votes
如果您可以将应用程序升级到C#6,那么您很幸运。 新的C#版本已实现了异常过滤器。 所以你可以这样写:
catch (Exception ex) when (ex is CommunicationException || ex is SystemException) {
//handle it
}
有人认为此代码与
catch (Exception ex) {
if (ex is CommunicationException || ex is SystemException) {
//handle it
}
throw;
}
但事实并非如此。 实际上,这是C#6中唯一无法在先前版本中模仿的新功能。 首先,重新抛出意味着比跳过捕获更多的开销。 其次,它在语义上并不等效。 调试代码时,新功能可以使堆栈保持原样。 如果没有此功能,则故障转储将变得不太有用甚至没有用。
请参阅有关CodePlex的讨论。 并显示差异的示例。
25 votes
实际上,您只能捕获SystemException
,它也可以处理CommunicationException
,因为CommunicationException
源自SystemException
catch (SystemException se) {
... //this handles both exceptions
}
11 votes
不幸的是,没有办法。 您使用的语法无效,并且也无法像switch语句中那样掉线。 我认为您需要使用私有方法。
一个小小的变通办法将是这样的:
var exceptionHandler = new Action<Exception>(e => { /* your three lines */ });
try
{
// code that throws
}
catch(CommuncationException ex)
{
exceptionHandler(ex);
}
catch(SystemException ex)
{
exceptionHandler(ex);
}
您需要自己决定是否有意义。
5 votes
不,您不能那样做。 我知道的唯一方法是捕获一个通用异常,然后检查它是什么类型:
try
{
...
}
catch(Exception ex)
{
if(ex is CommunicationException || ex is SystemException)
{
...
}
else
{
... // throw; if you don't want to handle it
}
}
3 votes
关于什么
try {
...
}
catch (CommunicationException ce) {
HandleMyError(ce);
}
catch {SystemExcetion se) {
HandleMyError(se);
}
private void HandleMyError(Exception ex)
{
// handle your error
}
3 votes
可能重复
一次捕获多个异常?
我在这里引用答案:
catch (Exception ex)
{
if (ex is FormatException ||
ex is OverflowException)
{
WebId = Guid.Empty;
return;
}
else
{
throw;
}
}
1 votes
由于您对两种类型的异常都执行相同的操作,因此可以执行以下操作:
try
{
//do stuff
}
catch(Exception ex)
{
//normal exception handling here
}
仅在需要为它做一些独特的事情时才捕获显式的Exception类型。