Java 正在为任何类型的异常引发不带“引发”的异常

Java 正在为任何类型的异常引发不带“引发”的异常,java,exception,Java,Exception,我想在Java中抛出任何类型的异常,但限制是我不能将抛出异常添加到我的主方法中。所以我试了一下: import java.io.IOException; class Util { @SuppressWarnings("unchecked") private static <T extends Throwable> void throwException(Throwable exception, Object dummy) throws T {

我想在Java中抛出任何类型的异常,但限制是我不能将抛出异常添加到我的主方法中。所以我试了一下:

import java.io.IOException;

class Util
{
    @SuppressWarnings("unchecked")
    private static <T extends Throwable> void throwException(Throwable exception, Object dummy) throws T
    {
        throw (T) exception;
    }

    public static void throwException(Throwable exception)
    {
        Util.<RuntimeException>throwException(exception, null);
    }
}

public class Test
{
    public static void met() {
        Util.throwException(new IOException("This is an exception!"));  
    }

    public static void main(String[] args)
    {
        System.out.println("->main");
        try {
            Test.met();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}
这段代码可以工作,但当我尝试在try-catch块中捕获IOException(例如)时,它不会编译。编译器告诉我永远不会抛出IOException。它仅适用于扩展RuntimeException的异常。有办法解决这个问题吗

增加:

import java.io.IOException;

class Util
{
    @SuppressWarnings("unchecked")
    private static <T extends Throwable> void throwException(Throwable exception, Object dummy) throws T
    {
        throw (T) exception;
    }

    public static void throwException(Throwable exception)
    {
        Util.<RuntimeException>throwException(exception, null);
    }
}

public class Test
{
    public static void met() { // this method's signature can't be changed
        Util.throwException(new IOException("This is an exception!"));  
    }

    public static void main(String[] args)
    {
        System.out.println("->main");
        try {
            Test.met();
        } catch (IOException e) { // can't be changed and it does not compile right now
            System.out.println(e.getMessage());

        }
    }
}
答案很简单:你不能

更复杂的答案是:你不能,你真的不应该这样做。主要原因是,如果您的代码能够捕捉到它没有发布到的异常,那么这将导致不一致和错误

最重要的是,除了IOException之外,该代码块不打算捕获任何东西;也就是说,该代码只用于在IO出现问题时进行恢复。如果我尝试捕获任何其他内容,那么这将意味着代码知道如何从该场景中恢复,而事实并非如此


顺便说一句,IOException的任何子项都会被该块捕获,因此您不必担心捕获FileNotFoundExection,因为这会处理它。

这是一个糟糕的编码,我觉得写它很脏

您可以检查捕获的异常是否是IOException,而不是直接捕获IOException


是:按照预期使用异常,而不是用肮脏的伎俩欺骗编译器。如果一个方法正在抛出一个IOException,它应该用throws声明它。如果不希望抛出,则使用运行时异常。或者使用一种选择不检查异常的JVM语言,比如Kotlin。我之所以使用它,是因为我需要在一个特定的上下文中使用它,在这个上下文中我无法更改方法签名…然后使用运行时异常,不是已检查的异常。我有以下情况:1我无法更改方法签名2我必须使一些已编写的try-catch块工作。抱歉,但这看起来像是一个懒惰的借口。重写需要正确重写的代码:无论如何,这些catch块显然不是用来捕获新的未声明IOException的。
public class Test
{
    public static void main(String[] args)
    {
        System.out.println("->main");
        try {
            Test.met();
        } catch (Exception e) {
            if (e instanceof IOException) {
                System.out.println(e.getMessage());
            }
        }
    }
}