Is there any valid reason to ever ignore a caught exception

后端 未结 24 1935
南笙
南笙 2020-11-27 15:43

Wow, I just got back a huge project in C# from outsourced developers and while going through my code review my analysis tool revealed bunches of what it considered bad stuff

24条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-27 16:25

    There are certainly circumstances where it's OK to catch a specific exception and do nothing. Here's a trivial example:

        public FileStream OpenFile(string path)
        {
            FileStream f = null;
            try
            {
                f = new FileStream(path, FileMode.Open, FileAccess.ReadWrite);
            }
            catch (FileNotFoundException)
            {
            }
            return f;
        }
    

    You could also write the method this way:

        public FileStream OpenFile(string path)
        {
            FileStream f = null;
            FileInfo fi = new FileInfo(path);
            if (fi.Exists)
            {
                f = new FileStream(path, FileMode.Open, FileAccess.ReadWrite);                
            }
            return f;
        }
    

    In this case, catching the exception is (very) marginally safer, as the file could get deleted between the time you check for its existence and the time you open it.

    There are reasons not to do this, sure. In .NET, exceptions are computationally expensive, so you want to avoid anything that throws a lot of them. (In Python, where exceptions are cheap, it's a common idiom to use exceptions to do things like break out of loops.)

    But that's ignoring a specific exception. This code:

    catch
    {
    }
    

    is inexcusable.

    There's no good reason not to catch the specific typed exception that the code in the try block is going to throw. The first reason that the naive developer gives for catching exceptions irrespective of type, "But I don't know what type of exception might get thrown," is kind of the answer to the question.

    If you don't know what type of exception might get thrown, you don't know how your code can fail. If you don't know how your code can fail, you have no basis for assuming that it's OK to just continue processing if it does.

提交回复
热议问题