user3805009
user3805009

Reputation: 3

When exception occurs is it possible to pause my try block, execute catch block and again resume my try block

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

When user enters integer value, i need to pause my execution then need to display "Enter valid input" and again have to remuse my try block. How can i achieve this in java..

Upvotes: 0

Views: 201

Answers (2)

Lucky
Lucky

Reputation: 106

Try this:

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;
}

Upvotes: 2

nobalG
nobalG

Reputation: 4620

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);

Upvotes: 0

Related Questions