简体   繁体   中英

Need to throw checked exception in implementation, but it's not thrown by the interface?

I'm implementing the Accumulo BatchWriter interface to perform some additional computation over records before inserting. That computation may throw a checked exception if something goes wrong, but the only exception thrown by BatchWriter is the MutationsRejectedException . As such, I'm unable to throw the necessary checked exception when an error occurs in the pre-processing I'm trying to do.

Now, I could catch the checked exception and simply throw another exception in its place: either an unchecked exception like some RuntimeException or a MutationsRejectedException. Neither option seems great - an unchecked exception is a poor simulacrum of the exception I'd like to actually throw while throwing a MutationsRejectedException wouldn't allow me to see the actual cause of the error.

What is the best practice here?

"MutationsRejectedException wouldn't allow me to see the actual cause of the error."

Yes MutationsRejectedException would allow you to see the actual cause via chained exceptions . Note the "Throwable cause" in the constructor. Code for version 1.7;

try{
    //...
} catch (Exception e) {
    throw new MutationsRejectedException(null, null, (Map<TabletId,Set<SecurityErrorCode>>)null, null, 1, e);
}

.

try{
    //...
} catch (MutationsRejectedException e) {
    Throwable c = e.getCause();
    if(c instanceof MyException){
        //...
    }else{
        throw e;
    }
}

The BatchWriter interface actually covers exactly your situation by expecting you to wrap whatever root cause you got into its MutationsRejectedException . That is much better design than declaring a general Exception and exception translation has been the recommended Java idiom since version 1.3 or so.

With throws Exception hopefully crossed out as an antipattern, all the choice you have is between exception translation and the "sneaky throw" idiom. I believe your preference would be the former, especially considering that the latter is very similar to having throws Exception , but more obscure.

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