Wrap every method in try-catch or specific part of code

前端 未结 5 955
星月不相逢
星月不相逢 2020-12-16 23:46

My senior colleague tells me to wrap every method within a try-catch block so they can trace where exceptions occurs to help debug issues quicker. Is it better to wrap every

5条回答
  •  星月不相逢
    2020-12-17 00:07

    Using try-catch depends strongly on the context. For me there's no rules to tell developer when using or not a try catch block.

    Developer code must prevent the evident errors or exceptions due to context like null parameters or file existence or the data coherency. In case of developing a library used by many other programs, the library catches only some critical exception to allow top level programs have more details about errors and exceptions.

    For example, we have a method in library using System.IO.File.WriteAllLines.

    void bool DoSomethingWithFile()
    {
      try
      {
         // Some code here
         System.IO.File.WriteAllLines()
         //some code here
         return true;
      }
      catch()
      {
         LogExeption();
         return false;
      }
    }
    

    How to tell top level program that the PathTooLongException or there's a security exception unless you add throw in the catch block.

提交回复
热议问题