简体   繁体   中英

Overriding method throws checked exception not defined in interface

Say I have an interface DataStore which has the method public List<Entity> getEntities() . The class SqlDataStore implements this interface. The thing is that when calling SqlDataStore.getEntities() an SQLException could be thrown. I cannot alter the interface to add this checked exception to the method signature, because you could also write an implementation XmlDataStore which is accessing XML files to fetch the data. What should I do to handle those checked exceptions the implementations could throw?

Okay, here is what I did in lack of better ideas. I defined a class DataStoreException that extended RuntimeException . I removed the throws clause from the interface definition. When a checked exception is thrown in one of the classes that implemented DataStore I just catch it and wrap it in DataStoreException and rethrow it.

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