Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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;
    }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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!");
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading