Why doesn't the program throw an exception despite typing the wrong type?

Advertisements

Why doesn’t exception handling work in this code?
It seems to me that I have implemented it well, after entering numbers of real type the application works fine, but when I enter for example random characters the program "terminates" but does not show the captured error message.

In the console I get: finished with non-zero exit value 1

import java.util.Scanner;

public class NewClass {
    public static void main(String[] args) {
        NewClass newClass = new NewClass();
        Scanner scanner = new Scanner(System.in);
        try {
            System.out.println("Enter the first side of the rectangle: ");
            double firstValue = scanner.nextDouble();
            System.out.println("Enter the second side of the rectangle: ");
            double secondValue = scanner.nextDouble();
            double result = newClass.calculateRectangleArea(firstValue, secondValue);
            System.out.println("Area of ​​a rectangle with sides " + firstValue + " " + "and" + secondValue + " " + "are" + result);
        } catch (NumberFormatException exception) {
            System.out.println("Please enter the correct type!");
        }
    }

    public double calculateRectangleArea(double a, double b) {
        return a * b;
    }
}

>Solution :

Your scanner.nextDouble() method call throws InputMismatchException when you enter a random character other than a valid double number. But you’ve caught NumberFormatException in your catch block. If you want to capture the above case you should’ve caught the InputMismatchException.

catch (InputMismatchException exception) {
    System.out.println("Please enter the correct type!");
}

Leave a ReplyCancel reply