0

I have a Login Method that is triggered by JButton Actionperformed.

private void loginButtonActionPerformed(java.awt.event.ActionEvent evt) {

    try {

        Users userData = userDAO.login(Integer.parseInt(loginUserId.getText()), String.valueOf(loginUserPassword.getPassword()));            

    } catch (SQLException ex) {
        LOGGER.log(Level.SEVERE, ex.toString(), ex);
        JOptionPane.showMessageDialog(null, "Error SQL: Please Contact your System Administrator", cf.WINDOW_TITLE, JOptionPane.ERROR_MESSAGE);  
    } catch (NullPointerException e) {
        JOptionPane.showMessageDialog(null, e.getMessage(), cf.WINDOW_TITLE, JOptionPane.ERROR_MESSAGE);  
    } catch (NumberFormatException e) {            
        JOptionPane.showMessageDialog(null, "Pls write a number", cf.WINDOW_TITLE, JOptionPane.ERROR_MESSAGE);  
    }
}

Here is my Method that returns an Object from the database.

public Users login(int userId, String password) throws NumberFormatException, SQLException , NullPointerException {

    SQL sql = new SQL();
    query = sql.createPStatement(cf.SELECT_USER_BY_LOGIN_DATA);        
    query.setInt(1, userId);
    query.setString(2, password);
    ResultSet resultSet = query.executeQuery();
    try {
        if (!resultSet.isBeforeFirst()) {              
            throw new NullPointerException("User Not Found");
        }
        while (resultSet.next()) {
            Users newLoggedUser = new Users();
            //Set Object Values
            return newLoggedUser;
        }
    } catch (SQLException e) {
        LOGGER.log(Level.SEVERE, e.toString(), e);
        throw e;
    }  
catch (NullPointerException e) {
        LOGGER.log(Level.SEVERE, e.toString(), e);
        throw e;
    } catch (NumberFormatException e) {
  LOGGER.log(Level.SEVERE, e.toString(), e);
        throw e;
    } finally {
        SQLUtils.closeQuietly(sql.dbConection());
        SQLUtils.closeQuietly(resultSet);
        SQLUtils.closeQuietly(query);            
    }
    return null;
}  

I have to show multiple error messages to the USER accorgding to:

  • User not found (No SQL result);
  • Type Letters instead of numbers
  • SQL Error.

I have some questions about this:

  1. Should I Stop the app to doing more actions Where my Results/Objects are NULL , using throw new NullPointerException("User Not Found");

  2. Is safely to use those exceptions to send User Messages, like in the case of Object is null ("User not Found"), and throw them by the DAO Method to be catched/Displayed by the JButton ActionPerformed try/Catch?

  3. Where I should log the exceptions, in the DAO Method? , or ActionPerformed try/Catch?.

  4. Should I throw e; again in DAO Method to be catched by ActionPerformed try/Catch?

Like Always thank you very much for your help.

  • 2
    You should almost never need to catch `NullPointerException`. It indicates that you (the programmer) is doing something incorrectly with respect to the language or the APIs you are using. – Andy Turner Feb 03 '17 at 14:43
  • 2
    `"throw new NullPointerException("User Not Found");"` You're not dereferencing a null reference, this isn't the right exception to use. How about a `NoSuchElementException` instead? – Andy Turner Feb 03 '17 at 14:44
  • "Type Letters instead of numbers" <- I would rather do a quick regex check before sending the data to your query function instead of relying on the NumberFormatException – OH GOD SPIDERS Feb 03 '17 at 14:47
  • @AndyTurner Thank you very much , by far Im a junior programmer trying to do the best I can. The `throw new NullPointerException("User Not Found");` was to stop the program to read all the method code , but If not neccesary I will remove it. I havent seen the `NoSuchElementException ` , thank you very much for the heads up. – Juan Sebastian Osorio Feb 03 '17 at 14:49
  • @AndyTurner How is that? , I did not know that. Because the object is null and the program crash if I dont catch the `NullpointerExpception`. You have any example to get me in the right path? . Thank you. – Juan Sebastian Osorio Feb 03 '17 at 14:53
  • @JuanSebastianOsorio see http://stackoverflow.com/questions/15146339/catching-nullpointerexception-in-java. – Andy Turner Feb 03 '17 at 14:57

1 Answers1

2
  1. IMO the best way to handle would be to create your own custom exception (extends Exception) like

    public class LoginException extends Exception{
      public LoginException(Exception cause, String message) {
        ..
      }
    }
    

You can use the message parameter to specify what to display to the client.

Wrap all of your possible login exceptions thru this, and declare it as thrown by your DB method

  1. Sure, It's safe. And many programs do this. But it's better to try to clarify the problem to the user.

  2. This requires us to state an opinion, which is off-topic. You could do it either way. But me, I'd do it in the actionPerformed, as the button click starts the "transaction".

  3. Same answer as 3

ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
  • Thank you very much!. I will Code the Class and update the question. – Juan Sebastian Osorio Feb 03 '17 at 14:59
  • How I can pass the Exception ? , Equally it needs to be try/Catched again in the LoginException.? Eg. `public LoginException(Exception e){ try { if(e.getClass() == NoSuchElementException.class){ JOptionPane.showMessageDialog(null, "User not Found"); } } catch (NoSuchElementException ex) { throw ex; } }` – Juan Sebastian Osorio Feb 03 '17 at 16:54
  • @JuanSebastianOsorio No. When you have an `Exceptional` condition from which you cannot proceed (ie transaction failure) You create the new LoginException just like any other object, and then throw it. It then bubbles up to your ActionListener, and there you can do `JOptionPane.showMessageDialog(null,ex.getMessage());` in the catch block – ControlAltDel Feb 03 '17 at 17:07
  • Something Like this ? [link](http://alvinalexander.com/java/java-custom-exception-create-throw-exception) But I do have to known with exception is thrown right? to Configure the Message. Thank you for your time. Your help is very appreciated. – Juan Sebastian Osorio Feb 03 '17 at 17:16
  • 1
    @JuanSebastianOsorio Yes, like they do in the link. As far as "But I do have to know which exception..." You described your error cases above. If no user is found, in that case you won't even have an exception, but you should throw your LoginException with a message: "User Not Found". If there's a SQL Exception: "Problem with the database..." If there are numbers, likewise: "Please use only characters for the user ID" – ControlAltDel Feb 03 '17 at 18:10