我不想抓住一些例外。我能以某种方式做到吗?
我可以这样说:
catch (Exception e BUT not CustomExceptionA)
{
}
答案 0 :(得分:21)
try
{
// Explosive code
}
catch (CustomExceptionA){ throw; }
catch (Exception ex)
{
//classic error handling
}
答案 1 :(得分:9)
try
{
}
catch (Exception ex)
{
if (ex is CustomExceptionA)
{
throw;
}
else
{
// handle
}
}
答案 2 :(得分:3)
您可以过滤它:
if (e is CustomExceptionA) throw;
当然,你可以抓住它并重新抛出它:
try
{
}
catch (CustomExceptionA) { throw; }
catch (Exception ex) { ... }
答案 3 :(得分:3)
Starting with C# 6, you can use an exception filter:
try
{
// Do work
}
catch (Exception e) when (!(e is CustomExceptionA))
{
// Catch anything but CustomExceptionA
}
答案 4 :(得分:2)
首先,除非您记录并重新抛出异常,否则捕获异常是不好的做法。但是,如果必须,您需要捕获自定义异常并重新抛出它:
try
{
}
catch (CustomExceptionA custome)
{
throw custome;
}
catch (Exception e)
{
// Do something that hopefully re-throw's e
}
答案 5 :(得分:-1)
在评论中受@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()
内的那一行会被悄悄地传递掉。