【问题标题】:multiple statements in try/catch block - Javatry/catch 块中的多个语句 - Java
【发布时间】:2014-10-17 18:12:19
【问题描述】:

我有点不确定这是否:

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

基本上希望用户输入一个数字,如果不是数字则抛出异常并重新要求用户输入一个数字?

谢谢

【问题讨论】:

    标签: java exception optimization try-catch joptionpane


    【解决方案1】:

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

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

    在第二个示例中,如果第一个try...catch 有异常,则不会向用户显示第二个问题,因为控制不会在try 块内继续,而是在catch 之后继续区块结束。

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:

        你也可以试试下面的代码

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

        更多详情请访问:Multiple try-catch in java with example

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-11-19
          • 1970-01-01
          • 1970-01-01
          • 2016-03-15
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多