简体   繁体   English

抛出异常时编译错误?

[英]compilation error while throwing exception?

What is wrong with this code? 这段代码有什么问题?

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();
        }
    }
}

As in pleaseThrow method throws SQLException still it gives Compilation error. pleaseThrow方法中抛出SQLException仍然会给出编译错误。

Error : 错误:

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

The problem is because you are throwing a RuntimeException , but trying to catch SQLException . 问题是因为您正在抛出RuntimeException ,但是尝试捕获SQLException

In your method, 在你的方法中,

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

You are casting the argument SQLException in your case to T (which is RuntimeException in your case and throwing it. 您将在您的情况下将参数SQLException转换为T (在您的情况下是RuntimeException并抛出它)。

So, the compiler is expecting a RuntimeException to be thrown and not SQLException . 因此,编译器期望抛出RuntimeException而不是SQLException

Hope this is clear. 希望这很清楚。

you would be able to write this when your pleaseThrow method actually throws SQLException . 当你的pleaseThrow方法实际抛出SQLException时,你可以写这个。

Currently what you are doing is just passing a object of type SQlExcetion as parameter to this method. 目前您正在做的只是将SQlExcetion类型的对象作为参数传递给此方法。

Currently what Compiler observes is you are calling a method and it does not throw any SQLException , so compiler deems the catch clause as a problem and shows this compilation problem 目前Compiler观察到的是你正在调用一个方法并且它不会抛出任何SQLException,因此编译器认为catch子句是一个问题,并显示了这个编译问题

Your pleaseThrow() does not throw an SQLException . 你的pleaseThrow()不会抛出SQLException You have some choices: make your catch to catch a generic Exception 你有一些选择:让你的catch来捕获一般的Exception

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

or make pleaseThrow(..) actually throw an SQLException 或者pleaseThrow(..)实际抛出一个SQLException

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

or actually throw an SQLException 实际抛出SQLException

new Mocker<SQLException>().pleaseThrow(new SQLException());

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

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