When to choose checked and unchecked exceptions

前端 未结 18 2296
南方客
南方客 2020-11-22 04:13

In Java (or any other language with checked exceptions), when creating your own exception class, how do you decide whether it should be checked or unchecked?

My inst

18条回答
  •  囚心锁ツ
    2020-11-22 04:48

    On any large enough system, with many layers, checked exception are useless as, anyway, you need an architectural level strategy to handle how the exception will be handled (use a fault barrier)

    With checked exceptions your error handling stategy is micro-managed and its unbearable on any large system.

    Most of the time you don't know if an error is "recoverable" because you don't know in what layer the caller of your API is located.

    Let's say that I create a StringToInt API that converts the string representation of an integer to an Int. Must I throw a checked exception if the API is called with the "foo" string ? Is it recoverable ? I don't know because in his layer the caller of my StringToInt API may already have validated the input, and if this exception is thrown it's either a bug or a data corruption and it isn't recoverable for this layer.

    In this case the caller of the API does not want to catch the exception. He only wants to let the exception "bubble up". If I chose a checked exception, this caller will have plenty of useless catch block only to artificially rethrow the exception.

    What is recoverable depends most of the time on the caller of the API, not on the writter of the API. An API should not use checked exceptions as only unchecked exceptions allows to choose to either catch or ignore an exception.

提交回复
热议问题