如何在Java中捕获异常?[关闭]

How to catch an exception in Java? [closed]

提问人:shoaib mohammed 提问时间:1/8/2013 最后编辑:Raedwaldshoaib mohammed 更新时间:9/18/2015 访问量:3710

问:


要求代码的问题必须表现出对所解决问题的最低限度的理解。包括尝试的解决方案、它们不起作用的原因以及预期的结果。Смотритетакже: Stack Overflow 问题清单

10年前关闭。

如何在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);
 ...
Java 异常

评论

1赞 Peter Lawrey 1/8/2013
您需要读取整个堆栈跟踪。您的代码中是否抛出了此异常?
1赞 Alvin Wong 1/8/2013
docs.oracle.com/javase/tutorial/essential/exceptionsdocs.oracle.com/javase/tutorial/essential/exceptions/try.htmldocs.oracle.com/javase/tutorial/essential/exceptions/catch.html
0赞 titogeo 1/8/2013
点击这里查看 docs.oracle.com/javase/tutorial/essential/exceptions
1赞 jlordo 1/8/2013
我希望您知道会出现异常,因为提交的数字太大而无法放入 .int
4赞 Alvin Wong 1/8/2013
如何真正知道该术语,但不知道如何使用异常?throwcatch

答:

4赞 radai 1/8/2013 #1
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赞 Jonathan 1/8/2013
那不应该吗?:-)Integer.parseInt
0赞 radai 1/8/2013
是的,它应该。这就是我从内存中编码得到的:-)
0赞 Bhavik Shah 1/8/2013
或者你可以把它扔掉,在调用函数中接住它
0赞 SomeJavaGuy 1/8/2013 #2

你有 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");
}
0赞 David Ruan 1/8/2013 #3
try { 
    //codes that thows the exception
} catch(NumberFormatException e) { 
    e.printTrace();
}
0赞 Tarrjue 1/8/2013 #4

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

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

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