![](/img/trans.png)
[英]Exception Handling with Scanner.nextInt() vs. Scanner.nextLine()
[英]Java Exception Handling for Scanner input: Clearing bad data with nextLine (catch vs Finally)
当您在异常捕获中调用input.nextLine()时,最好将其放置在每个catch块中或放在try-catch末尾的finally块中。 两种方法的优点或缺点是什么?
例:
catch (InputMismatchException e)
{
input.nextLine();
System.out.println("Cannot add to Database, please enter only integers");
}
catch (Exception e)
{
input.nextLine();
System.out.println("Impossible to add, please enter only letters from a-z");
}
要么
catch (InputMismatchException e)
{
System.out.println("Cannot add to Database, please enter only integers");
}
catch (Exception e)
{
System.out.println("Impossible to add, please enter only letters from a-z");
}
finally
{
input.nextLine();
}
两种方法的优点或缺点是什么?
问候,
丸。
如果您想不考虑异常条件(不管是否处理异常引发了异常)都读取下一行,请在finally
块中写入input.nextLine()
。 如果只想在引发异常并对其进行处理时才读取下一行,则在相应的catch
块中写入input.nextLine()
。
catch
, finally
是不同的用法。 finally
不关心异常类型等,所以,使用finally
,当您需要执行的代码是否该方法工艺好不好。
catch
约例外类型的医疗服务。 因此,您可以在出现例外情况时进行处理。 因为您不希望应用程序崩溃。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.