2013-01-08 87 views
-16

如何捕捉Java中的异常?我有一个程序接受用户输入的整数值。现在如果用户输入一个无效值,它会抛出一个java.lang.NumberFormatException。我如何捕获该异常?如何在Java中捕捉异常?

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

您需要读取整个堆栈跟踪。这个异常是否在你的代码中抛出? –

+1

http://docs.oracle.com/javase/tutorial/essential/exceptions/和http://docs.oracle.com/javase/tutorial/essential/exceptions/try.html和http://docs.oracle。 com/javase/tutorial/essential/exceptions/catch.html –

+0

请点击这里http://docs.oracle.com/javase/tutorial/essential/exceptions/ – titogeo

回答

4
try { 
    int userValue = Integer.parseInt(aString); 
} catch (NumberFormatException e) { 
    //there you go 
} 

特别

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"); 
} 
+1

不应该是'Integer.parseInt'吗? :-) – Jonathan

+0

是的,它应该。这就是我从内存编码得到的:-) – radai

+0

或者你可以扔它,并在调用函数中捕获它 –

0

你有try和catch块:在你的代码

public void actionPerformed(ActionEvent e) { 
     String str; 
     int no; 
     if (e.getSource() == bb) { 
      str = JOptionPane.showInputDialog("Enter quantity"); 
      no = Integer.parseInt(str); 
... 
0
try { 
    //codes that thows the exception 
} catch(NumberFormatException e) { 
    e.printTrace(); 
} 
0

其值得一提的是很常见的许多程序员去捕捉这样的异常:

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

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