I have built this class up from various post as good as i could.
I am trying to get a list of usernames from a MySQL database.
Here is the method retrieving them:
public ArrayList<String> LoadUsers() throws SQLException {
ArrayList<String> players = new ArrayList<String>();
try {
Connection conn = null;
ResultSet rs = null;
try {
conn = getConnection();
Statement s = conn.createStatement ();
s.executeQuery ("SELECT * FROM NFT_users");
rs = s.getResultSet ();
while(rs.next ()){
players.add(rs.getString("name"));
}
rs.close ();
s.close ();
}
catch (SQLException ex) {
System.out.println(ex.toString());
}
finally {
try {
if (conn != null) conn.close();
}
catch (SQLException ex) {
System.out.println("On close: " + ex.toString());
}
}
}
catch(Exception ex) {
//trace(ex);
}
return players;
}
And this is the code in my mainclass which retrieves it from the method:
ArrayList<String> players = database.LoadUsers();
However, i get the error Must be caught or declared to be thrown. What do i do wrong?
Your method: –
has declared an
SQLExceptionin it’s throws clause. So, from whichever method you call this method from, you would either need to enclose theinvocationin atry-catchblock to handle this exception, or declare this exception in the throws clause of that method also.So, suppose you are calling your method from a method
caller().So, you have two options: –
Declare exception in
throwsclause ofcaller: –Enclose the method invocation in a try-catch. In this case, remember to declare your
listoutside the block first:Note that, if you are using the first option, then you will again face same problem in the method that called
caller. There also you would have to follow this thing.In general, an exception raised inside a method is – either handled there using try-catch block, or is propagated up the stack trace to the immediate caller method, but not both. You are doing both in your method. You are handling the exception, and have declared it to be thrown in the
throwsclause too. You should never do that.