Should I catch and wrap general Exception?

前端 未结 14 1162
一向
一向 2020-12-30 04:19

Can following code be considered as a good practice? If not, why?

try
{
    // code that can cause various exceptions.         


        
14条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-30 05:00

    No, generally, you should not do that: this may mask the real exception, which may indicate programming issues in your code. For example, if the code inside the try / catch has a bad line that causes an array index out of bound error, your code would catch that, too, and throw a custom exception for it. The custom exception is now meaningless, because it reports a coding issue, so nobody catching it outside your code would be able to do anything meaningful with it.

    On the other hand, if the code inside the try / catch throws exceptions that you expect, catching and wrapping them in a custom exception is a good idea. For example, if your code reads from some special file private to your component, and the read causes an I/O exception, catching that exception and reporting a custom one is a good idea, because it helps you hide the file operation from the caller.

提交回复
热议问题