Finally does not end

Discussion in 'Programming' started by MrSpomg, Sep 14, 2018 at 9:53 PM.

  1. Ok so I get this code and everyting is executed properly. However, the code won't get to the return statement and it gets like bugged. Any idea? Thanks!

    Code (Java):
        public Set<be.maximvdw.spigotsite.api.user.User> getBuyers() {
            final Set<be.maximvdw.spigotsite.api.user.User> value = new HashSet<>();
            Statement stm = null;
            ResultSet result = null;

            try {
                stm = data.createStatement();
                result = stm.executeQuery("SELECT id FROM buyers");
           
                while (result.next()) {
                    try {
                        value.add(bot.getSpigot().getUserManager().getUserById(result.getInt("id")));
                    } catch (ConnectionFailedException | PermissionException ex) {
                        LogHelper.logException("An error occurred while connecting to Spigot.", ex);
                    }
                }
            } catch (SQLException ex) {
                LogHelper.logException("An error occurred while connecting to the database.", ex);
            } finally {
                if (result != null) {
                    try {
                        result.close();
                    } catch (SQLException ex) {
                        LogHelper.logException("An error occurred while connecting to the database.", ex);
                    }
                }

                if (stm != null) {
                    try {
                        stm.close();
                    } catch (SQLException ex) {
                        LogHelper.logException("An error occurred while connecting to the database.", ex);
                    }
                }
            }
       
            return value; //<-- Never returned or reached!
     
  2. I can understand that this could take a long time to complete with a big or even medium sized table of buyers. Could you limit the amount of buyers that the query returns by adding LIMIT 0,10

    Code (Text):
                result = stm.executeQuery("SELECT id FROM buyers LIMIT 0,10");
         
                while (result.next()) {
                    try {
                        value.add(bot.getSpigot().getUserManager().getUserById(result.getInt("id")));
                    } catch (ConnectionFailedException | PermissionException ex) {
                        LogHelper.logException("An error occurred while connecting to Spigot.", ex);
                    }
                }
     
  3. The thing is that the buyers mysql is empty. And the code inside the finally block executes just after the code inside try. However, it does not pass from finally.
     
  4. Got it working the thing is that a variable was null and the try-catch-finally clause was masking the NPE. Thanks!
     

Share This Page