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

后端 未结 7 2284
一向
一向 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 17:04

    I generally use the same type of code structure, but condense it down to one line in one of the few times a ternary operator actually makes code better:

    try {
      // code that can throw
    }
    catch (Exception e) {
      throw (e instanceof RuntimeException) ? (RuntimeException) e : new RuntimeException(e);
    }
    

    This does not require additional methods or catch blocks which is why I like it.

提交回复
热议问题