如何在Java中捕获异常?

时间:2013-01-08 13:09:58

标签: java exception exception-handling

如何在Java中捕获异常?我有一个程序接受整数值的用户输入。现在,如果用户输入无效值,则会抛出java.lang.NumberFormatException。我如何捕获该异常?

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

4 个答案:

答案 0 :(得分:4)

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

,特别是在您的代码中:

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
}

答案 1 :(得分:0)

你有尝试并抓住阻止:

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");
}

答案 2 :(得分:0)

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

答案 3 :(得分:0)

值得一提的是,许多程序员常常捕获这样的异常:

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

即使他们知道问题是什么,也不想在catch子句中做任何事情。它只是很好的编程,可以作为一个非常有用的诊断工具。