Kei*_*ler 14 c# exception-handling
可能重复:
一次捕获多个异常?
在C#中有什么方法可以轻松实现以下pseduo代码:
try
{
...
}
catch ( ExceptionTypeA, ExceptionTypeB, ExceptionTypeC as ex)
{
... same code for all threw
}
Run Code Online (Sandbox Code Playgroud)
要么
try
{
...
}
catch ( ExceptionTypeA ex )
catch ( ExceptionTypeB ex )
catch ( ExceptionTypeC ex )
{
... same code for all exceptions of A, B or C
}
Run Code Online (Sandbox Code Playgroud)
我想我所说的将是很好的将在异常类型上落空.
Mar*_*ell 16
提到的语法问题(带有ex
)是:什么属性/成员应该ex
有?不同的异常类型不一定兼容,除非涉及继承(在这种情况下,捕获您关心的最少派生).
唯一的当前选项是在处理程序中使用Exception ex
(或类似)和检查(is
/ as
).
要么; 将公共代码重构为一个可以被所有三个使用的方法?
简而言之,没有.我可以想到两个三个选择:
捕获每个异常,并调用一个常用方法:
try
{
// throw
}
catch ( ExceptionTypeA ex )
{
HandleException();
}
catch ( ExceptionTypeB ex )
{
HandleException();
}
catch ( ExceptionTypeC ex )
{
HandleException();
}
void HandleException()
{
}
Run Code Online (Sandbox Code Playgroud)
或者捕获所有内容,并在类型上使用if语句:
try
{
// throw
}
catch (Exception ex)
{
if (ex is ArgumentException || ex is NullReferenceException || ex is FooException)
{
// Handle
}
else
{
throw
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:或者,你可以做这样的事情:
List<Type> exceptionsToHandle = new List<Type>{ typeof(ArgumentException), typeof(NullReferenceException), typeof(FooException) };
try
{
// throw
}
catch (Exception ex)
{
if (exceptionsToHandle.Contains(ex.GetType()))
{
// Handle
}
else
{
throw
}
}
Run Code Online (Sandbox Code Playgroud)
您可以捕获一般异常,然后检查类型,例如:
catch (Exception ex)
{
if (ex is ExceptionTypeA ||
ex is ExceptionTypeB )
{
/* your code here */
}
else
{
throw;
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:与其他答案一致,我希望通过拉出一种方法来阐明正在发生的事情-但我可能会引入一种方法来澄清if语句的内容,而不是使用单个捕获和通用方法在做。所以代替
if (ex is ExceptionTypeA || ex is ExceptionTypeB )
Run Code Online (Sandbox Code Playgroud)
它会变成这样的:
if (IsRecoverableByDoingWhatever(ex))
Run Code Online (Sandbox Code Playgroud)
我认为这比拉出处理程序代码更能阐明目的(尽管这样做可能也很有用)。
归档时间: |
|
查看次数: |
7953 次 |
最近记录: |