2014-10-17 98 views
3

林有点不确定这是否:多个语句在try/catch块 - Java的

try{ 
     worldHeight = Integer.parseInt(JOptionPane.showInputDialog("How many cells high will the world be?: ")); 
     } 
     catch (NumberFormatException e){ 
      JOptionPane.showMessageDialog(null, "You have not entered a valid number"); 
     } 

    try{ 
     worldWidth = Integer.parseInt(JOptionPane.showInputDialog("How many cells wide will the world be?: ")); 
     } 
     catch (NumberFormatException e){ 
      JOptionPane.showMessageDialog(null, "You have not entered a valid number"); 
     } 

会做同样的事情:

try{ 
     worldHeight = Integer.parseInt(JOptionPane.showInputDialog("How many cells high will the world be?: ")); 
     worldWidth = Integer.parseInt(JOptionPane.showInputDialog("How many cells wide will the world be?: ")); 
     } 
     catch (NumberFormatException e){ 
      JOptionPane.showMessageDialog(null, "You have not entered a valid number"); 
     } 

基本上要用户输入一个数字,如果它不是一个数字异常被抛出并且用户被重新请求一个数字?

谢谢

回答

3

在第一个示例中,使用两个单独的try...catch块,似乎在引发异常时,您只是显示一个对话框,而不是停止控制流。

因此,如果在第一个try...catch中出现异常,控制将继续到第二个try...catch,并且将要求用户输入第二个号码,而不管她没有正确输入第一个号码。

在第二示例中,如果在所述第一try...catch一个异常,则用户将不与第二个问题提出,因为控制不会在try块内继续,而是catch块的结束之后。

0

是的,这将工作(几乎)相同。在try catch块中,它只会在发生错误的地方停止执行。如果它在第一行发生错误,第二行将永远不会在第二个选项中执行。这是唯一的区别,在第一个选项中,无论第一行(输入)是否引发错误,都会执行第二行(输入)。