抛出异常时编译错误?

时间:2015-08-07 12:01:18

标签: java exception exception-handling try-catch

此代码有什么问题?

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

3 个答案:

答案 0 :(得分:3)

问题是因为您正在抛出SQLException,但却试图抓住private void pleaseThrow(final Exception t) throws T{ throw (T)t; }

在您的方法中,

SQLException

您正在将案例中的T投射到RuntimeException(在您的情况下为RuntimeException并抛出它。

因此,编译器期望抛出SQLException而不是dgv.ShowRowErrors

希望这很清楚。

答案 1 :(得分:2)

当您的pleaseThrow方法实际抛出SQLException时,您就可以写下此内容。

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

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

答案 2 :(得分:2)

您的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());
相关问题