如何在Java中捕获异常?
如何在Java中捕获异常?我有一个程序,接受用户输入的整数值。现在,如果用户输入一个无效值,它将抛出一个如何在Java中捕获异常?,java,exception,exception-handling,Java,Exception,Exception Handling,如何在Java中捕获异常?我有一个程序,接受用户输入的整数值。现在,如果用户输入一个无效值,它将抛出一个java.lang.NumberFormatException。我如何捕获该异常 public void actionPerformed(ActionEvent e) { String str; int no; if (e.getSource() == bb) { str = JOptionPane.showInp
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);
...
特别是在您的代码中:
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
}
您已经有了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");
}
值得一提的是,对于许多程序员来说,捕捉这样的异常是很常见的:
try
{
//something
}
catch(Exception e)
{
e.printStackTrace();
}
即使他们知道问题是什么,或者不想在catch子句中做任何事情。它只是一个很好的编程工具,是一个非常有用的诊断工具。您需要读取整个堆栈跟踪。您的代码中是否引发了此异常?检查这里,我希望您知道异常发生了,因为提交的数字太大,无法放入
int
中。您如何知道术语throw
和catch
但不知道如何使用异常?这不应该是Integer.parseInt
?:-)是的,应该是这样。这就是我从内存编码得到的:-)或者你可以抛出它并在调用函数中捕获它
try {
//codes that thows the exception
} catch(NumberFormatException e) {
e.printTrace();
}
try
{
//something
}
catch(Exception e)
{
e.printStackTrace();
}