-1

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;
    }
}
diho472
  • 69
  • 5
  • You need `scanner.nextLine();` in your catch block to swallow the invalid token that is still held by the Scanner object. – Hovercraft Full Of Eels Feb 07 '23 at 12:08
  • @user16320675 Sorry, I misspelled. The program terminates and the console displays the message `finished with non-zero exit value 1` but already the colleague below gave the solution :) – diho472 Feb 07 '23 at 12:18

1 Answers1

2

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!");
}
Subramanian Mariappan
  • 3,736
  • 1
  • 14
  • 29