Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
310 views
in Technique[技术] by (71.8m points)

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

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 shouldn't ? Or there is more to it ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...