Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAVA - Having difficulties with Try / Catch

Tags:

java

try-catch

I'm writing a straight forward Airport Terminal style program for class. I'm going beyond the scope of the assignment and "attempting" to use Try/Catch blocks...

However Java is being that guy right now.

The problem is that when someone enters a non-letter into the following code it doesn't catch then return to the try block it caught...

Why?

Edit - Also the containsOnlyLetters method works, unless someone thinks that could be the error?

System.out.println("\nGood News! That seat is available");

try
{//try
    System.out.print("Enter your first name: ");
    temp = input.nextLine();
        if (containsOnlyLetters(temp))
            firstName = temp;
        else
            throw new Exception("First name must contain"
                    + " only letters");

    System.out.print("Enter your last name: ");
    temp = input.nextLine();
        if (containsOnlyLetters(temp))
            lastName = temp;
        else
            throw new Exception("Last name must contain"
                    + " only letters");
}//end try

catch(Exception e)
{//catch
    System.out.println(e.getMessage());
    System.out.println("\nPlease try again... ");
}//end catch

passengers[clients] = new clientInfo
            (firstName, lastName, clients, request, i);
bookSeat(i);
done = true;
like image 973
Kid Programmer Avatar asked Feb 12 '26 06:02

Kid Programmer


1 Answers

You seem to misunderstand the purpose and mechanism of try/catch.

It's not intended for general flow control, and more specifically, the meaning is not that the try block is repeated until it finishes without an exception. Instead, the block is run only once, the point is that the catch block will only execute if a matching exception is thrown.

You should use a while loop and if clauses for your code, not try/catch.

like image 195
Michael Borgwardt Avatar answered Feb 14 '26 19:02

Michael Borgwardt