[英]multiple statements in try/catch block - 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");
}
基本上希望用户输入一个数字,如果不是数字异常被抛出并且用户被重新询问一个数字?
谢谢
在您的第一个示例中,使用两个单独的try...catch
块,似乎抛出异常时,您只是显示一个对话框,而不是停止控制流。
因此,如果在第一次try...catch
有异常,则控制将继续到第二次try...catch
并且将要求用户输入第二个数字,而不管她没有进入第一个数字正确。
在第二个示例中,如果第一个try...catch
存在异常,则不会向用户显示第二个问题,因为控件不会在try
块内继续,而是在catch
块结束后继续。
是的,这将(几乎)相同。 在try catch块中,它只会在发生错误的位置停止执行。 如果它在第一行抛出错误,则第二行永远不会执行第二行。 这是唯一的区别,在第一个选项中,无论第一行(输入)是否抛出错误,都将执行第二行(输入)。
您也可以尝试以下代码
{
int arr[]=new int[5];
try
{
try
{
System.out.println("Divide 1");
int b=23/0;
}
catch(ArithmeticException e)
{
System.out.println(e);
}
try
{
arr[7]=10;
int c=22/0;
System.out.println("Divide 2 : "+c);
}
catch(ArithmeticException e)
{
System.out.println("Err:Divide by 0");
}
catch(ArrayIndexOutOfBoundsException e)
//ignored
{
System.out.println("Err:Array out of bound");
}
}
catch(Exception e)
{
System.out.println("Handled");
}
}
有关更多详细信息,请访问: 带有示例的java中的多个try-catch
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.