简体   繁体   中英

How to properly use try-catch?

I'm trying to process how to use try-catch. I understand it'll 'try' the main code, and if it doesn't work it'll catch it and execute something different. I want to also keep prompting the user to enter a proper value.

I keep getting the inputmismatch exception error, even if I set my catch to have that in its block.

To clarify: The try-catch is going to be there for when I ask the user for ints on how long they plan to stay, and what floor they'd like to be on. Therefore, the errors I'd like to handle involve non-integers and if they are out of bounds of the 'hotel'.

Here is my code:

public class Hotel{

   public static void main(String[] args) throws IOException {
      int choice = 0;
      String guestName = " ";
      int stayTime = 0;
      int floorPref = 0;

      System.out.println("Welcome to the Hotel California.");
      Scanner sc = new Scanner(System.in);


      Room[][] hotel = new Room[8][20];         


      for(int i = 0; i< hotel.length; i++){
         for(int j = 0; j<hotel[i].length;j++){
            hotel[i][j] = new Room(0,false,"none",0.00,0);

            int roomNum = ((i+1) * 100) + (j + 1);
            hotel[i][j].setRoom(roomNum);

            int roomCheck = hotel[i][j].getRoomNumber();

            if(roomCheck > 500){
               hotel[i][j].setPrice(350.00);   
            }

            else if(roomCheck < 500){
               hotel[i][j].setPrice(200.00);
            } 
         }
      }

       // Guest check-in interface.

      do{

         System.out.println("What business have you today?");
         System.out.println("1. Guest Registration");
         System.out.println("2. Guest Checkout");
         System.out.println("3. Show me occupied rooms");
         System.out.println("4. Exit");

         choice = sc.nextInt();

         if(choice == 1){  


            System.out.println("Tell us about yourself.");

            System.out.println("Please input your name:");

            guestName = sc.next();

            System.out.print("How long are you planning to stay?");

            try{
               stayTime = sc.nextInt();
            }
            catch(InputMismatchException e){
               System.out.println("Please input a valid integer.");
               stayTime = sc.nextInt();
            }

            System.out.println("Great. What floor would you like to be on? Enter a number 1-8, 0 for no preference.");

            floorPref = sc.nextInt();

            System.out.println("The following rooms are available based on your floor preference (floors 1-8, 0 for no preference: ");

         }    
         if(floorPref > 0){

            for(int i = 0; i < hotel[floorPref].length; i++){
               if(hotel[floorPref][(i)].getOccupation() == false){


                  System.out.print("Rooms " +  hotel[floorPref-1][i].getRoomNumber() + ", ");


               }
            }

            System.out.println("Are available today.");
         }


         else if(floorPref == 0){
            for(int i = 0; i < hotel.length; i++){
               for(int j = 0; j < hotel[i].length; j++){
                  System.out.print("Room " +  hotel[i][j].getRoomNumber() + ", ");

               }
            }

            System.out.println("Is available.");

         }


      }while(choice != 4);


   }
}

The try-catch block you have right now is flawed, because once you get inside the catch block, all the user has to do is enter something that's not an integer to crash your whole program.

Instead, to get stayTime and all the other ints you pull from the Scanner , create a separate function that blocks until the user enters an int:

private static int parseIntFromScanner(Scanner sc) {
    while(true) {
        try {
            int toReturn = sc.nextInt();
            return toReturn;
        } catch(InputMismatchException ime) {
            //Continue back to the top of the loop, ask again for the integer
        }
    }
}

try to put this at the top of your code

import java.util.InputMismatchException;
import java.util.Scanner;
import java.io.IOException;

and in your public static void throws IOException main delete throws IOException so it only remains public static void main hope it will works

the following is small piece of code to divide.If user enters zero then it will go to catch and you can also enter number. Note the code will go catch only once.I have used depracated methods.This is just an example as per your requirement.

import java.io.DataInputStream;
import java.io.IOException;


public class test1 {
    public static void main(String args[]) throws NumberFormatException, IOException
    {
        DataInputStream d=new DataInputStream(System.in);int x;
        try {
             x=Integer.parseInt(d.readLine());
            int z=8;
            System.out.println(z/x);
        } catch (Exception e)
        {
            System.out.println("can not divide by zero");
            x=Integer.parseInt(d.readLine());
        }
    }

}

To answer your question as to why it's still failing: all of the calls to nextInt() can throw InputMistmatchException , not only the one put inside the try part of a try-catch block. And that's what's happening now.

Another issue is calling nextInt a second time inside the catch block. Exceptions thrown inside a catch block require their own handling, separate from the try-catch block to which they belong. So, if nextInt inside the catch block throws an InputMismatchException , it will leave the try-catch block and work its way out from there. In the case of the posted code, that means main will terminate on the exception.

A side point, as musical_coder pointed out, the code needs to loop with the validation. Otherwise, it would end up without setting values if the second attempt to read a value fails.

BTW, see this: Redoing a try after catch in Java , for a tip on scanner use that will lead to more headaches. In fact, it tells why the handling with the try-catch you have now will always end up terminating the program. (it's a matter of how Scanner functions)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM