How to wrap checked exceptions but keep the original runtime exceptions in Java

后端 未结 7 2268
一向
一向 2020-12-15 16:36

I have some code that might throw both checked and runtime exceptions.

I\'d like to catch the checked exception and wrap it with a runtime exception. But if a Runtim

7条回答
  •  無奈伤痛
    2020-12-15 16:58

    Not really.

    If you do this a lot, you could tuck it away into a helper method.

    static RuntimeException unchecked(Throwable t){
        if (t instanceof RuntimeException){
          return (RuntimeException) t;
        } else if (t instanceof Error) { // if you don't want to wrap those
          throw (Error) t;
        } else {
          return new RuntimeException(t);
        }
    }
    
    try{
     // ..
    }
    catch (Exception e){
       throw unchecked(e);
    }
    

提交回复
热议问题