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