【发布时间】:2012-09-06 13:44:46
【问题描述】:
我不想捕获一些异常。我能做到吗?
我可以这样说吗:
catch (Exception e BUT not CustomExceptionA)
{
}
?
【问题讨论】:
-
捕获并重新抛出您列入白名单的异常?
标签: c# .net exception-handling
我不想捕获一些异常。我能做到吗?
我可以这样说吗:
catch (Exception e BUT not CustomExceptionA)
{
}
?
【问题讨论】:
标签: c# .net exception-handling
try
{
// Explosive code
}
catch (CustomExceptionA){ throw; }
catch (Exception ex)
{
//classic error handling
}
【讨论】:
try
{
}
catch (Exception ex)
{
if (ex is CustomExceptionA)
{
throw;
}
else
{
// handle
}
}
【讨论】:
从 C# 6 开始,您可以使用 exception filter:
try
{
// Do work
}
catch (Exception e) when (!(e is CustomExceptionA))
{
// Catch anything but CustomExceptionA
}
【讨论】:
throw; 那样破坏原始堆栈。
你可以过滤它:
if (e is CustomExceptionA) throw;
当然,你可以抓住它并重新抛出它:
try
{
}
catch (CustomExceptionA) { throw; }
catch (Exception ex) { ... }
【讨论】:
throw 而不是 throw e 将使堆栈跟踪大部分保持完好。
首先,除非您记录并重新抛出异常,否则捕获异常是不好的做法。但如果必须,您需要捕获自定义异常并像这样重新抛出它:
try
{
}
catch (CustomExceptionA custome)
{
throw custome;
}
catch (Exception e)
{
// Do something that hopefully re-throw's e
}
【讨论】:
在 cmets 中接受 @Servy 的教育后,我想到了一个解决方案,可以让你做 [我认为的] 你想做的事情。让我们创建一个方法IgnoreExceptionsFor(),如下所示:
public void PreventExceptionsFor(Action actionToRun())
{
try
{
actionToRun();
}
catch
{}
}
然后可以这样调用:
try
{
//lots of other stuff
PreventExceptionsFor(() => MethodThatCausesTheExceptionYouWantToIgnore());
//other stuff
}
catch(Exception e)
{
//do whatever
}
这样,除了PreventExceptionsFor() 的那一行之外的每一行都会正常抛出异常,而PreventExceptionsFor() 里面的那一行会被悄悄地通过。
【讨论】:
try 中的代码在异常被重新抛出后将不会继续。
var a Session["whatever"]; if(a==null) a=default(A); 这样的东西如果 Session 抛出一个 nullref 或其他东西,谁在乎,我们仍然希望获得默认值。我的答案是唯一允许这样做的。
the only logical reason anyone would want to rethrow an exception is to catch it elsewhere 那,或者这是一个致命的异常,应该让应用程序崩溃。请注意,他没有说过任何暗示想要你所要求的行为。如果那是他想要的,那么他需要提出要求。此外,您的答案不涉及不引发异常,这似乎是您认为 OP 想要的。您的回答基本上是,“明确捕获除扩展Exception 的自定义异常之外的所有异常”。这不是一个特别实用的选择。