Search code examples
exceptiontry-catch

Try-Catch sum two numbers


I'm working on Exception Handling and making a new Java Project.Program waits for user type 2 numbers from keyboard. If user types two integer numbers it'll sum these numbers. If user doesn't type numbers program will print 'Type numbers!' on screen. Here's What I Tried:

public static void main(String[] args) {
    int a = 0;
    int b = 0;
    System.out.println("Type two numbers");
    Scanner scan = new Scanner(System.in);
    try {
        a = scan.nextInt();
        b = scan.nextInt();
    } catch (Exception ex) {
        System.err.println("Type number!");
    }
}

Solution

  • Try code below. It should work as you expect:

    public static void main(String[] args) {
        System.out.println("Type two numbers");
        sum();
    }
    
    private static void sum(){
        int a = 0;
        int b = 0;
        Scanner scan = new Scanner(System.in);
        try {
            a = scan.nextInt();
            b = scan.nextInt();
            System.out.println(a+b);
        } catch (Exception ex) {
            System.err.println("Type numbers in correct format!");
            sum();
        }
    }