Multiple statements in a try / catch block - Java

Slightly not sure what this is:

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

      

will do the same as:

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

      

basically want the user to enter a number if it is not selected to exclude a number and the user is prompted for a number?

thank

+3


source to share


2 answers


In the first example with two separate blocks, try...catch

it seems that when an exception is thrown, you are just showing the dialog without stopping the control flow.

As a result, if try...catch

there is an exception in the first , control will continue until the second try...catch

, and the user will be prompted to enter the second number, regardless of the fact that she did not enter the first number correctly.



In the second example, if try...catch

there is an exception in the first , the user will not be asked the second question because control will not continue inside the block try

, but rather after the catch

end of the block.

+3


source


Yes, this will work (almost) the same. In the try catch block, it stops execution only at the point where the error occurs. If it throws an error on the first line, the second line will never be executed on the second. This is the only difference: in the first option, the second line (input) will be executed regardless of whether the first line (input) picked an error or not.



0


source







All Articles