Reputation: 8103
I want to catch SQLException
on the try-catch block of Foo
method and here is my code which is not working actually;
public int Foo() {
try {
DB.delete("table", "fname=" + name);
} catch (SQLException e) {
LOGGER.log(Level.WARNING, e.getMessage());
}
}
public int delete(String table, String conditions) {
int updatedRow = 0;
try {
String sql = "DELETE FROM " + table + " SET " + " WHERE " + conditions;
updatedRow = SPM_Database.opeStmt.executeUpdate(sql);
} catch (SQLException ex) {
System.out.println("message" + ex);
LOGGER.log(Level.WARNING, ex.getMessage());
}
return updatedRow;
}
I've got error from catch-block inside Foo() method in my IDE which is;
Unreachable catch block for
SQLException
This exception is never thrown from the try-block. Why I cannot use the try-catch block? Is that I need to throw SQLException
from delete() function or any ideas?
Upvotes: 4
Views: 11474
Reputation: 11602
Add a throw
statement in your catch block after what you need to do is complete. And also you need to add throws SQLException
on your method signature.
public int delete(String table, String conditions) throws SQLException { // signature is changed
int updatedRow = 0;
try {
String sql = "DELETE FROM " + table + " SET " + " WHERE " + conditions;
updatedRow = SPM_Database.opeStmt.executeUpdate(sql);
} catch (SQLException ex) {
System.out.println("message"+ ex);
LOGGER.log(Level.WARNING, ex.getMessage());
throw ex; // <== ADD THIS LINE
}
return updatedRow;
}
Upvotes: 0
Reputation: 1086
The methode delete needs to throw the exception so Foo can catch it.
public int delete(String table, String conditions) throws SQLException{
int updatedRow = 0;
String sql = "DELETE FROM " + table + " SET " + " WHERE " + conditions;
updatedRow = SPM_Database.opeStmt.executeUpdate(sql);
return updatedRow;
Foo remains as it is.
good luck!
Upvotes: 2
Reputation: 393801
Your delete
method can never throw a SQLException
, since it doesn't declare it in a throws
clause. Therefore, your catch clause in Foo
is unreachable.
You don't need to throw SQLException
from the delete
method, but you also don't need to surround the call to delete
with a try block and you don't need to catch SQLException
.
Upvotes: 5