Can I not catch a specific or custom exception?

2020-04-05 08:01发布

I dont want to catch some exception. Can I do it somehow?

Can I say something like this:

catch (Exception e BUT not CustomExceptionA)
{
}

?

6条回答
闹够了就滚
2楼-- · 2020-04-05 08:26
try
{
      // Explosive code
}
catch (CustomExceptionA){ throw; }
catch (Exception ex)
{
    //classic error handling
}
查看更多
贼婆χ
3楼-- · 2020-04-05 08:29

You can filter it:

if (e is CustomExceptionA) throw;

And of course you can catch it and rethrow it:

try
{
}
catch (CustomExceptionA) { throw; }
catch (Exception ex) { ... }
查看更多
戒情不戒烟
4楼-- · 2020-04-05 08:37

After being schooled by @Servy in the comments, I thought of a solution that'll let you do [what I think] you want to do. Let's create a method IgnoreExceptionsFor() that looks like this:

public void PreventExceptionsFor(Action actionToRun())
{
    try
    {
         actionToRun();
    }
    catch
    {}
}

This can then be called like this:

try
{
     //lots of other stuff
     PreventExceptionsFor(() => MethodThatCausesTheExceptionYouWantToIgnore());
     //other stuff
}
catch(Exception e)
{
    //do whatever
}

That way, every line except for the one with PreventExceptionsFor() will throw exceptions normally, while the one inside PreventExceptionsFor() will get quietly passed over.

查看更多
闹够了就滚
5楼-- · 2020-04-05 08:41
try
{
}
catch (Exception ex)
{
    if (ex is CustomExceptionA)
    {
        throw;
    }
    else
    {
        // handle
    }
}
查看更多
淡お忘
6楼-- · 2020-04-05 08:41

Starting with C# 6, you can use an exception filter:

try
{
    // Do work
}
catch (Exception e) when (!(e is CustomExceptionA))
{
    // Catch anything but CustomExceptionA
}
查看更多
▲ chillily
7楼-- · 2020-04-05 08:44

First off, it's bad practice to catch Exception unless you log and re-throw it. But if you must, you need to catch your custom exception and re-throw it like so:

try
{
}
catch (CustomExceptionA custome)
{
    throw custome;
}
catch (Exception e)
{
    // Do something that hopefully re-throw's e
}
查看更多
登录 后发表回答