Replace a checked exception with a runtime exception?

后端 未结 6 1401
情话喂你
情话喂你 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:56

    Project Lombok allows you to disable checked exceptions altogether.

    0 讨论(0)
  • 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);
    }
    
    0 讨论(0)
  • 2021-02-06 05:03

    As of Java 8 there's another way:

    try {
      // some code that can throw both checked and runtime exception
    } catch (Exception e) {
      throw rethrow(e);
    }
    
    @SuppressWarnings("unchecked")
    public static <T extends Throwable> RuntimeException rethrow(Throwable throwable) throws T {
        throw (T) throwable; // rely on vacuous cast
    }
    

    * More info here.

    0 讨论(0)
  • 2021-02-06 05:04

    Follow up from my comment. Here's an article that has to throw some light on the issue. It uses sun.misc.Unsafe to rethrow exceptions without wrapping them.

    0 讨论(0)
  • 2021-02-06 05:12

    sounds like you actually NEED checked Exceptions

    0 讨论(0)
  • 2021-02-06 05:16

    If you're considering the other answer's use of Unsafe (I recommend not, but anyway), another option is to abuse generics to throw a checked exception with this evil pair of methods (from http://james-iry.blogspot.co.uk/2010/08/on-removing-java-checked-exceptions-by.html):

       @SuppressWarnings("unchecked")
       private static <T extends Throwable, A> 
         A pervertException(Throwable x) throws T {
          throw (T) x;
       }
    
    
       public static <A> A chuck(Throwable t) {
          return Unchecked.
            <RuntimeException, A>pervertException(t);
       }
    

    You might also check out com.google.common.base.Throwables.getRootCause(Throwable) and just print its (root) stack trace.

    0 讨论(0)
提交回复
热议问题