Add the following code snippet to handle NumberFormatException
using a try-catch block:
try {
String invalidStringFloat = "NumberFormatException";
float invalidFloat = Float.parseFloat(invalidStringFloat);
System.out.println("Parsed float value: " + invalidFloat);
} catch (NumberFormatException e) {
System.out.println("Invalid string value!");
}
In this step, we add a try-catch
block to handle the NumberFormatException
that is thrown when an invalid string value is parsed to float
data type. Inside the try
block, we attempt to parse an invalid string value invalidStringFloat
to float
data type. If a NumberFormatException
is thrown due to an invalid string value, the code inside the catch
block is executed which prints an error message "Invalid string value!" to the console.