Search code examples
javainputtry-catchnumberformatexception

Catch-block with NumberFormatException is being ignored?


I am trying to send an error JOptionPane when the user enters invalid or nothing at all. I am trying to do this with a try/catch block and a NumberFormatException but it seems to me, that the block is being ignored, but this can't be.

import javax.swing.*;

import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.lang.NumberFormatException;

public abstract class Input extends JFrame implements ActionListener { 

     public static void main(String[] args) throws NumberFormatException {

    //implementation of the GUI with JTexFields etc.

    try {
        button.addActionListener(e -> {
            Label.setText(" ");

            int Num1 = 5;

            int Num2 = Integer.valueOf(Field1.getText());

            if (Num1 <= 0) {
                //something;
            }

            //calculate with input 
       });
   }
    catch (NumberFormatException e) {
        JOptionPane.showMessageDialog(null,
                "Please watch out for your input.",
                "Input error",                        
        JOptionPane.ERROR_MESSAGE);
    }
}
}   

I'm sorry that the code probably isn't according to the code conventions but I cut out all unimportant parts and so, I maybe made the code 'uglier'.


Solution

  • Put the try catch block in the action listener. The action listener is a different class so your current try catch block won't catch exceptions in it.