Reputation: 1034
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.
Error :
Unreachable catch block for SQLException. This exception is never thrown from the try
statement body
Upvotes: 2
Views: 1210
Reputation: 2201
Your pleaseThrow()
does not throw an SQLException
. You have some choices: make your catch
to catch a generic Exception
catch (final Exception e) {
// TODO: handle exception
e.printStackTrace();
}
or make pleaseThrow(..)
actually throw an SQLException
private void pleaseThrow(final Exception t) throws SQLException{
throw (SQLException)t;
}
or actually throw an SQLException
new Mocker<SQLException>().pleaseThrow(new SQLException());
Upvotes: 2
Reputation: 14471
The problem is because you are throwing a RuntimeException
, but trying to catch 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.
So, the compiler is expecting a RuntimeException
to be thrown and not SQLException
.
Hope this is clear.
Upvotes: 3
Reputation: 3831
you would be able to write this when your pleaseThrow
method actually throws SQLException
.
Currently what you are doing is just passing a object of type SQlExcetion
as parameter to this method.
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
Upvotes: 2