提问人:shoaib mohammed 提问时间:1/8/2013 最后编辑:Raedwaldshoaib mohammed 更新时间:9/18/2015 访问量:3710
如何在Java中捕获异常?[关闭]
How to catch an exception in Java? [closed]
问:
如何在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赞
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 子句中做任何事情。它只是很好的编程,可以是一个非常有用的诊断工具。
上一个:如何在 Java 中比较字符串?
下一个:在聚合物元素之间共享数据更改
评论
int
throw
catch