[英]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.