Java中的try-catch-Python-retry等价物
我对java非常陌生,我正在尝试错误处理。我对python非常在行,我知道python中的错误处理会很好
while True:
try:
*some code*
except IndexError:
continue
break
我想知道java中异常后重试循环的等价物是什么
编辑: 这就是我到目前为止所做的,但是每当抛出异常时,它都会执行一个无限循环,说“输入一个简短的错误:重试”
while(true)
{
try {
System.out.print("Enter an Short: "); //SHORT
short myShort = reader.nextShort();
System.out.println(myShort);
break;
}
catch (InputMismatchException e) {
System.out.println("Error Try again.");
continue;
}
}
澄清我到底想要什么。当抛出“InputMismatchException”时,循环将重新运行并再次提示用户,直到用户给出正确的输入。我希望这澄清了我希望它做什么
# 1 楼答案
当您的问题询问错误处理时,您以
IndexError
为例,Java中的等价物可以是:关于
ArrayIndexOutOfBoundsException
,你来看看here, in the documentation。关于例外,一般来说,你可以阅读here编辑,根据你的问题编辑,添加更多信息
在这种情况下,当
InputMismatchException
发生时,会显示错误消息,break
应该离开循环。我还不知道我是否理解你的要求,但我希望这能有所帮助# 2 楼答案
你所拥有的几乎和@Thomas提到的一样好。只需要添加一些括号和分号。它应该像下面的代码一样
# 3 楼答案
在@Slaw的帮助下,他决定扫描器将继续输入相同的值,除非我在循环结束时关闭它,这是工作代码