简体   繁体   English

将未经检查的异常抛出。 有什么办法可以防止在运行时?

[英]Throwing checked exception as unchecked. Is there any way to prevent in runtime?

With the simplified code I can throw Checked Exception without catching (the same way as uncheked). 使用简化的代码,我可以抛出Checked Exception而不会捕获(与取消锁定相同)。 From javadoc about RuntimeException - Compile-Time Checking of Exceptions . 从javadoc中获取有关RuntimeException的信息- 异常的编译时检查 Is there any way to prevent the behavior in runtime? 有什么方法可以防止运行时的行为?

import java.io.IOException;

public class TestException {

    static <E extends Exception>

    void doThrow(final Exception e) throws E {
        throw (E) e;
    }

    public static void main(String[] args) {
        TestException.<RuntimeException>doThrow(
              new IOException("Checked exception thrown")
        );
    }

}

Yes, correct the method signature to: 是的,将方法签名更正为:

static <E extends Exception> void doThrow(final E e) throws E {
    throw e;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM