Can I not catch a specific or custom exception?

后端 未结 6 1579
余生分开走
余生分开走 2021-01-18 02:16

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条回答
  •  情话喂你
    2021-01-18 03:01

    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.

提交回复
热议问题