JAVA-12

Q.12 Write a Java code that handles the custom exception like when a user gives input as Floating point number then it raises exception with appropriate message.

Solution  :- 

import java.util.*;

// Custom exception class
class FloatingPointInputException extends Exception {
    public FloatingPointInputException(String message) {
        super(message);
    }
}

public class CustomExceptionExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter an integer: ");
        
        try {
            if (scanner.hasNextFloat() && !scanner.hasNextInt()) {
                throw new FloatingPointInputException("Floating-point numbers are not allowed! Please enter an integer.");
            }
            int number = scanner.nextInt();
            System.out.println("You entered: " + number);
        } catch (FloatingPointInputException e) {
            System.out.println("Exception: " + e.getMessage());
        } finally {
            scanner.close();
        }
    }
}

TRY IT YOURSELF

Leave a Reply

Your email address will not be published. Required fields are marked *

sign up!

We’ll send you the hottest deals straight to your inbox so you’re always in on the best-kept software secrets.