Replace a checked exception with a runtime exception?

后端 未结 6 1409
情话喂你
情话喂你 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 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  RuntimeException rethrow(Throwable throwable) throws T {
        throw (T) throwable; // rely on vacuous cast
    }
    

    * More info here.

提交回复
热议问题