Java 如果我在每个catch块中调用input.nextLine()作为异常捕获的一部分,或者在try catch结束时在最后一个块中调用input.nextLine()是否有区别?
例如,这里我只放了一次,但我知道我可以放几次。有什么区别Java 如果我在每个catch块中调用input.nextLine()作为异常捕获的一部分,或者在try catch结束时在最后一个块中调用input.nextLine()是否有区别?,java,Java,例如,这里我只放了一次,但我知道我可以放几次。有什么区别 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
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");
}
}
试试看{
如果(tasks.size()finally
将始终被调用,无论您是否发出异常,这是有区别的
无论如何,假设您使用的是Scanner
,您应该避免使用try-catch作为逻辑的一部分(只有在发生异常情况时才应使用try-catch,因为创建异常可能会很昂贵)。相反,请尝试使用hasNextInt
方法来避免抛出异常
因此,您可以尝试以下方法:
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)
区别在于清晰和简单
如果存在,finally
块将始终执行。整个块通用的代码可以在那里找到。将来如果需要不同的响应,可以在单个位置更改
当常见代码分布在多个位置时,您可能会更改某些但不是所有实例,从而导致意外故障。您的问题不清楚。此外,提供的代码与问题标题不匹配。请回答问题,以获得更好的答案(并避免结束问题)。