Search code examples
javaexceptionoptimizationtry-catchjoptionpane

multiple statements in try/catch block - Java


Im a bit uncertain as to whether this:

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

would do the same thing 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 isnt a number exception gets thrown and the user gets re-asked for a number?

Thanks


Solution

  • In your first example, with the two separate try...catch blocks, it seems that when an exception is thrown, you are just showing a dialog, not stopping the flow of control.

    As a result, if there is an exception in the first try...catch, control will continue to the second try...catch and the user will be asked to enter the second number, regardless of the fact that she did not enter the first number correctly.

    In the second example, if there is an exception in the first try...catch, the user will not be presented with the second question, because control will not continue inside the try block, but rather after the catch block's end.