-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
{
    //something
}
catch(Exception e)
{
    e.printStackTrace();
}

問題が何であるかを知っているか、catch句で何もしたくない場合でも。そのちょうど良いプログラミングであり、非常に便利な診断ツールになる可能性があります。

于 2013-01-08T14:21:55.973 に答える
0

あなたはtryと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 に答える