I'm always getting the default NumberFormatException message when the variables d1 and d2 are not of the proper data type.
I want to print my custom Exception message when those exceptions are caught using the throw statement conditionals.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a numeric value: ");
String input1 = sc.nextLine();
Double d1 = Double.parseDouble(input1);
System.out.print("Enter a numeric value: ");
String input2 = sc.nextLine();
Double d2 = Double.parseDouble(input2);
System.out.print("Choose an operation (+ - * /): ");
String input3 = sc.nextLine();
try {
if (!(d1 instanceof Double)) {
throw (new Exception("Number formatting exception caused by: "+d1));
}
if (!(d2 instanceof Double)) {
throw (new NumberFormatException("Number formatting exception caused by: "+d2));
}
switch (input3) {
case "+":
Double result = d1 + d2;
System.out.println("The answer is " + result);
break;
case "-":
Double result1 = d1 - d2;
System.out.println("The answer is " + result1);
break;
case "*":
Double result2 = d1 * d2;
System.out.println("The answer is " + result2);
break;
case "/":
Double result3 = d1 / d2;
System.out.println("The answer is " + result3);
break;
default:
System.out.println("Unrecognized Operation!");
break;
}
}
catch (Exception e){
System.out.println(e.getMessage());
}
}
}
This is an example of the message printed when entered value is not of proper format.
Enter a numeric value: $ Exception in thread "main" java.lang.NumberFormatException: For input string: "$" at java.base/jdk.internal.math.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2054) at java.base/jdk.internal.math.FloatingDecimal.parseDouble(FloatingDecimal.java:110) at java.base/java.lang.Double.parseDouble(Double.java:543) at com.example.java.Main.main(Main.java:13)