问题描述
这段代码有什么问题?
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
1楼
问题是因为您正在抛出RuntimeException
,但是尝试捕获SQLException
。
在你的方法中,
private void pleaseThrow(final Exception t) throws T{
throw (T)t;
}
您将在您的情况下将参数SQLException
转换为T
(在您的情况下是RuntimeException
并抛出它)。
因此,编译器期望抛出RuntimeException
而不是SQLException
。
希望这很清楚。
2楼
当你的pleaseThrow
方法实际抛出SQLException
时,你可以写这个。
目前您正在做的只是将SQlExcetion
类型的对象作为参数传递给此方法。
目前Compiler观察到的是你正在调用一个方法并且它不会抛出任何SQLException,因此编译器认为catch子句是一个问题,并显示了这个编译问题
3楼
你的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());