How to catch an exception in Java? [closed]

久未见 提交于 2019-12-13 23:24:54

问题


How to catch an exception in Java? I have a program that accepts user input which is of integer value. Now if the user enters an invalid value, it throws a java.lang.NumberFormatException. How do I catch that exception?

    public void actionPerformed(ActionEvent e) {
        String str;
        int no;
        if (e.getSource() == bb) {
            str = JOptionPane.showInputDialog("Enter quantity");
            no = Integer.parseInt(str);
 ...

回答1:


try {
   int userValue = Integer.parseInt(aString);
} catch (NumberFormatException e) {
   //there you go
}

and specifically in your code:

public void actionPerformed(ActionEvent e) {
    String str;
    int no;
    //------------------------------------
    try {
       //lots of ifs here
    } catch (NumberFormatException e) {
        //do something with the exception you caught
    }

    if (e.getSource() == finish) {
        if (message.getText().equals("")) {
            JOptionPane.showMessageDialog(null, "Please Enter the Input First");
        } else {
            leftButtons();

        }
    }
    //rest of your code
}



回答2:


you have got try and catch blocks :

try {
    Integer.parseInt(yourString);
    // do whatever you want 
}
//can be a more specific exception aswell like NullPointer or NumberFormatException
catch(Exception e) {
    System.out.println("wrong format");
}



回答3:


try { 
    //codes that thows the exception
} catch(NumberFormatException e) { 
    e.printTrace();
}



回答4:


Its worth mentioning that it is common for many programmers to catch an exception like so:

try
{
    //something
}
catch(Exception e)
{
    e.printStackTrace();
}

Even if they know what the problem is or doesnt want to do anything in the catch clause. Its just good programming and can be a pretty useful diagnostic tool.



来源:https://stackoverflow.com/questions/14215694/how-to-catch-an-exception-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!