Search code examples
javaswingnullpointerexceptiontry-catchjoptionpane

JOptionPane gives a NullPointerException and is not displayed


here is a code snippet

private void viewscriptJButtonActionPerformed(ActionEvent evt){                                                  

    try{
        for (int j = 0; j <= i; j++) {
            scriptPane.setText(queryList.get(j).toString() + "\n");
        }
    }
    catch(Exception e)
    {
       JOptionPane.showMessageDialog(this,"error:\n"+e.getMessage().toString() + "\n" + e.getCause().toString() ,"Error",JOptionPane.ERROR_MESSAGE);
    }
}

The code inside catch block always gives a NullPointerException .This is just a reference. The problem occurs with every button click event whenever an exception is needed to be caught. Any help.


Solution

  • You will find that Exception#getCause() returns null when the cause of the exception is itself, thus your e.getCause().toString() will throw a NullPointerException. The getCause method is generally used for finding the root exception when chaining them together.

    printStackTrace() will print out the entire Stack Trace of the exception, allowing for an easier time debugging, however to fix this error, just change your JOptionPane statement to:

    JOptionPane.showMessageDialog(this,"error:\n"+e.getMessage().toString(),"Error",JOptionPane.ERROR_MESSAGE);
    

    Also, you may want to see this.