-18

如何在 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

4 回答 4

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
}
于 2013-01-08T13:12:07.740 回答
0

你有 try and catch 块:

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");
}
于 2013-01-08T13:12:33.567 回答
0
try { 
    //codes that thows the exception
} catch(NumberFormatException e) { 
    e.printTrace();
}
于 2013-01-08T13:13:12.550 回答
0

值得一提的是,对于许多程序员来说,捕获这样的异常是很常见的:

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

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

于 2013-01-08T14:21:55.973 回答