General Exception Handling Strategy for .NET

后端 未结 11 1494
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-15 08:51

I’m used to having try/catch blocks in every method. The reason for this is so that I can catch every exception at the point of infraction and log it. I understand, from my

11条回答
  •  误落风尘
    2020-12-15 09:50

    OK, having read all the answers saying you should have a single try/catch at the top level, I'm going to weigh in with an alternative view.

    I wouldn't put a try/catch in every method, far from it. But I would use a try/catch around sections of code that I expected to fail (e.g. opening a file), and where I wanted to add additional information to the exception (to be logged higher up the chain).

    A stack trace saying and a message saying "permission denied" might be enough to allow you as a programmer to figure out what went wrong, but my goal is to provide the user with meaningful information, such as "Could not open file 'C:\lockedfile.txt'. Permission denied.".

    As in:

    private void DoSomethingWithFile(string filename)
    {
        // Note: try/catch doesn't need to surround the whole method...
    
        if (File.Exists(filename))
        {
            try
            {
                // do something involving the file
            }
            catch (Exception ex)
            {
                throw new ApplicationException(string.Format("Cannot do something with file '{0}'.", filename), ex);
            }
        }
    }
    

    I'd also like to mention that even the people saying "only have one try/catch" would presumably still use try/finally throughout their code, since that's the only way to guarantee proper cleanup, etc.

提交回复
热议问题