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

后端 未结 7 2277
一向
一向 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:14

    I have a specially compiled .class file containing the following:

    public class Thrower {
        public static void Throw(java.lang.Throwable t) {
            throw t;
        }
    }
    

    It just works. The java compiler would normally refuse to compile this, but the bytecode verifier doesn't care at all.

    The class is used similar to Peter Lawrey's answer:

    try {
      // some code that can throw both checked and runtime exception
    
    } catch (Exception e) {
        Thrower.Throw(e);
    }
    

提交回复
热议问题