开发者

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

开发者 https://www.devze.com 2022-12-18 09:46 出处:网络
API doc says never catch Throwable subclass Error which signifies abnormal behavior. Does it implies that the segregation between Error and Exception is to tell programmers that which subclass should

API doc says never catch Throwable subclass Error which signifies abnormal behavior. Does it implies that the segregation between Error and Exception is to tell programmers that which subclass should be caught and which 开发者_Go百科shouldn't ? Or there is more to it ?


In general, Error is something seriously wrong (often within the platform itself) which you could not conceivably handle. The only times I have ever cared about catching Error is in order to log it, following which I then re-throw.

This is vitally important as it is easy to let errors (and runtime exceptions) propagate up the call stack in such a way that they are never logged (e.g. using executorService.submit(Runnable) without listening to the returned Future)

Errors are usually things like:

  • out of memory
  • abstract method error (e.g. running against different version of libraries to those built against)
  • Assertions (i.e. programmer-defined invariants, or things that should never happen - lol!)

I would then say that RuntimeExceptions are usually (though not always) indicative of programming errors:

  • not checking for null, or passing in null
  • passing in invalid arguments, or allowing invalid state
  • modifying a collection as you are iterating over it

I would usually recommend failing-fast on these as well but this is a grey area; perhaps you don't check user input before passing it to the server -hardly worth crashing your app over!

Checked Exceptions (i.e. non-runtime) should be used for stuff that you could reasonably expect to happen and reasonably (or conceivably) handle in your code. Personally I like checked exceptions but these are rendered cumbersome because of the verbosity/repetition involved in handling distinct exception types in the same manner (i.e. in multiple identical catch blocks). Languages such as Scala have much better catch syntax, but then they removed the concept of checked exceptions as well!


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消