当前位置: 代码迷 >> java >> 抛出异常时编译错误?
  详细解决方案

抛出异常时编译错误?

热度:63   发布时间:2023-07-25 20:08:51.0

这段代码有什么问题?

public class Mocker<T extends Exception> {
    private void pleaseThrow(final Exception t) throws T{
        throw (T)t;
    }
    public static void main(String[] args) {
        try{
            new Mocker<RuntimeException>().pleaseThrow(new SQLException());
        }
        catch (final SQLException e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }
}

pleaseThrow方法中抛出SQLException仍然会给出编译错误。

错误:

Unreachable catch block for SQLException. This exception is never thrown from the try 
 statement body

问题是因为您正在抛出RuntimeException ,但是尝试捕获SQLException

在你的方法中,

private void pleaseThrow(final Exception t) throws T{
    throw (T)t;
}

您将在您的情况下将参数SQLException转换为T (在您的情况下是RuntimeException并抛出它)。

因此,编译器期望抛出RuntimeException而不是SQLException

希望这很清楚。

当你的pleaseThrow方法实际抛出SQLException时,你可以写这个。

目前您正在做的只是将SQlExcetion类型的对象作为参数传递给此方法。

目前Compiler观察到的是你正在调用一个方法并且它不会抛出任何SQLException,因此编译器认为catch子句是一个问题,并显示了这个编译问题

你的pleaseThrow()不会抛出SQLException 你有一些选择:让你的catch来捕获一般的Exception

        catch (final Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }

或者pleaseThrow(..)实际抛出一个SQLException

    private void pleaseThrow(final Exception t) throws SQLException{
        throw (SQLException)t;
    }

实际抛出SQLException

new Mocker<SQLException>().pleaseThrow(new SQLException());
  相关解决方案