Search code examples
java

try—catch can‘t catch the exception,cause when exception happend,enter recursion in catch ,try block dont work and just into the catch block


package object.myobject;

import java.util.Scanner;

public class CatchTheException {
    Scanner scanner = new Scanner(System.in);

    void receiveInt(){
        System.out.println("please input an int");
        try{
            System.out.println(scanner.nextInt());
            System.out.println("try block wont work");
        }catch (Exception e){
            System.out.println(e);
            System.out.println("the input is wrong, please input again");
            receiveInt();
        }
    }

    public static void main(String[] args) {
        new CatchTheException().receiveInt();

    }
}

I don't know why the try block wont work,maybe is the exception not catched? I’m a newbie of the try catch. i run and try block wont work make the recursion wont stop, so i get a stackoverflow exception


Solution

  • Here An Alternative way to do this sort of thing:

    Scanner scanner = new Scanner(System.in);
    String num = "";
    while (num.isEmpty()) {
        System.out.print("Please enter an integer value: -> ");
        num = scanner.nextLine().trim();
        /* Is the supplied value a string representation of a
           signed or unsigned integer value?     */
        if (!num.matches("-?\\d+")) {
            System.out.println("Invalid Entry (" + num + ")! Try again...\n");
            num = ""; // Ensure re-loop
        }
    }
            
    // Passed entry validation:
    int number = Integer.parseInt(num);  // Convert string value to Integer type:
    System.out.println("Your Number: -> " + number);