-2

For example, here I put it only once, but I know that I can put it several times. What is the difference?

        try{
        if(tasks.size() <= 0){
            System.out.println("Nothing to remove, no tasks");
        }
        else{
            System.out.println("Enter index of task to remove");
            int index = input.nextInt();
            input.nextLine();
            tasks.remove(index);
        }
    }
    catch(InputMismatchException ex){
        System.out.println("Please enter only numbers");
    }
    catch(IndexOutOfBoundsException ex){
        System.out.println("Invalid index number");
    }
}
Abc
  • 3
  • 2
  • It's unclear what you're asking. Also, the code provided doesn't match the title of the question. Please [edit](http://stackoverflow.com/posts/33704283/edit) the question in order to receive better answers (and to avoid closing the question). – Mick Mnemonic Nov 14 '15 at 01:53

2 Answers2

1

finally will be called always, regardless if you cough exception or not so yes, there is a difference.

Anyway assuming you are using Scanner you should avoid using try-catch as part of your logic (they should be used only if exceptional situations happen since creating exception may be expensive). Instead try to prevent throwing exceptions with little help of hasNextInt method.

So you can try with something like:

System.out.println("Enter index of task to remove");
while (!input.hasNextInt()){
    System.out.println("That was not proper integer, please try again");
    input.next();// to let Scanner move to analysing another value from user 
                 // we need to consume that incorrect value. We can also use 
                 // nextLine() if you want to consume entire line of 
                 // incorrect values like "foo bar baz"
}
//here we are sure that inserted value was correct
int int index = input.nextInt();
input.nextLine();// move cursor after line separator so we can correctly read 
                 // next lines (more info at http://stackoverflow.com/q/13102045/1393766)
Pshemo
  • 113,402
  • 22
  • 170
  • 242
0

The difference is clarity and simplicity.

The finally block will always execute, if present. Code which is common to the entire block can be located there. In the future if a different response is required it can be changed in a single location.

When common code is spread out in multiple locations you run the risk of changing some but not all instances which can result in unexpected failures.

Greg
  • 1,420
  • 3
  • 15
  • 26