Which subclass of Throwable should be caught and which shouldn't?

后端 未结 2 2077
旧时难觅i
旧时难觅i 2020-12-18 08:31

API doc says never catch Throwable subclass Error which signifies abnormal behavior. Does it implies that the segregation between Error and

2条回答
  •  轮回少年
    2020-12-18 09:05

    Yes, I think your analysis is correct here - you are not supposed to catch Errors because they represent runtime errors that can not be recovered from, such as OutOfMemoryError.

    The only reason to catch Throwable is if you are running external third-party code that is not needed for the correct operation of your program - if you don't trust that code, catch everything and if you get stuff that you didn't expect (Throwable) then disable that code and report it.

    Also it might be a good idea to distinguish between Exception and RuntimeException.

提交回复
热议问题