try/catch block-Java中的多个语句
我有点不确定这是否:try/catch block-Java中的多个语句,java,exception,optimization,try-catch,joptionpane,Java,Exception,Optimization,Try Catch,Joptionpane,我有点不确定这是否: try{ worldHeight = Integer.parseInt(JOptionPane.showInputDialog("How many cells high will the world be?: ")); } catch (NumberFormatException e){ JOptionPane.showMessageDialog(null, "You have not ente
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");
}
}
欲了解更多详情,请访问: