简体   繁体   中英

Wrapping an unchecked exception into a checked exception in Java

I am reading code written by others. Both unchecked exception and checked exception are custom exceptions. I see that an unchecked exception is thrown inside a method and it is wrapped into checked exception in a catch clause and thrown again. It is a common practice to wrap an unchecked exception into a checked exception? If yes, why do we do that?

Custom unchecked exceptions are a culprit in "leaky abstractions."

An application might define an interface for a service that it depends on. If the implementation throws implementation-specific unchecked exceptions that the application would like to handle specifically, it becomes polluted with implementation-specific exception types. This causes a maintenance headache if the implementation is replaced.

To avoid this problem, the unchecked exceptions might be wrapped in implementation-neutral checked exceptions defined by the interface.

As a concrete example, consider Hibernate's use of unchecked exceptions to notify callers of constraint violations. Suppose you have a User entity and the user name has a unique constraint defined in the database. You'd like to handle this condition specially, by prompting the user for a different name. If Hibernate's ConstraintViolationException propagates unchanged up the stack, the application will need Hibernate-specific handlers. On the other hand, if the data access layer wraps this in a suitable custom checked exception, replacing Hibernate with a new ORM implementation won't require any changes beyond the implementation layer.

If you do that in a method meth it is probably because the code calling
meth will need to only know about and check for the checked exception.
Say if meth can throw 5 different types of unchecked exceptions,
you make this more uniform and allow the calling code to worry only
about the checked one. But of course you can use unchecked exception
for this wrapping too. It is just that the compiler won't be able to
help you much in the calling code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM