发生异常时,可以暂停我的try块,执行catch块并再次恢复try块

时间:2014-07-28 07:15:26

标签: java exception-handling

try
{
  System.out.println("Enter your name");
        Name = in.next();
}
catch (InputMismatchException exception) {
        System.out.println("Enter valid input");
    }

当用户输入整数值时,我需要暂停执行,然后需要显示"输入有效输入"并再次不得不重新尝试我的尝试块。我怎样才能在java中实现这一点..

2 个答案:

答案 0 :(得分:2)

试试这个:

while(true)
{
    try
    {
      System.out.println("Enter your name");
            Name = in.next();
            break;
    }
    catch (InputMismatchException exception) {
            System.out.println("Enter valid input");

    }
    in.next();
    continue;
}

答案 1 :(得分:0)

int flag=0;
do{
try
{
  System.out.println("Enter your name");
        Name = in.next();
int num=Integer.parseInt(Name);//this line will generate exception if entered input is not integer
}
catch (InputMismatchException exception) {
        System.out.println("Enter valid input");
flag=1;//only run if the  Numberformatexception is generated(i.e integer was not entered)
    }
}while(flag==0);