[英]Is there difference if I call input.nextLine() as part of exception catching in every catch block or inside a final block at the end of try-catch?
比如这里我只放了一次,但是我知道我可以放几次。 有什么不同?
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");
}
}
finally
将始终被调用,无论您是否咳嗽异常,所以是的,这是有区别的。
无论如何,假设您正在使用Scanner
您应该避免使用 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
块将始终执行(如果存在)。 整个块共有的代码可以位于那里。 将来如果需要不同的响应,可以在一个位置进行更改。
当公共代码分布在多个位置时,您可能会更改一些但不是所有实例,这可能会导致意外故障。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.