Replace a checked exception with a runtime exception?

后端 未结 6 1405
情话喂你
情话喂你 2021-02-06 04:51

Given that I basically want to eliminate checked exception usage and transform them to runtime exceptions, I would normally be doing something like this:

try {
          


        
6条回答
  •  清歌不尽
    2021-02-06 04:57

    class IORuntimeException extends RuntimeException {
    
        final IOException ioex;
    
        public IORuntimeException(IOException ioex) {
            this.ioex = ioex;
        }
    
        @Override
        public String getMessage() {
            return ioex.getMessage();
        }
    
        @Override
        public StackTraceElement[] getStackTrace() {
            return ioex.getStackTrace();
        }
    
        //@Override
        // ...
    }
    

    (Full class available here, as produced by Eclipse "Generate Delegate Methods" macro.)

    Usage:

    try {
        ...
    } catch (IOException ioex) {
        throw new IORuntimeException(ioex);
    }
    

提交回复
热议问题