Skip to main content Skip to docs navigation
TechSpiderTutorials

java.lang.NumberFormatException in Java

On this page

Java.lang.NumberFormatException Class

Thrown to indicate that the application has attempted to convert a string to one of the numeric types, but that the string does not have the appropriate format.

Creating Objects

Default Constructor: This creates an instance without a message.

NumberFormatException ex1 = new NumberFormatException();
					

Constructor with Message:You can also pass a custom error message.

NumberFormatException ex2 = new NumberFormatException("Invalid number format");
					

NumberFormatException Class Example

public class NumberFormatExceptionExample {
    public static void main(String[] args) {
        String invalidNumber = "abc123"; // This is not a valid integer

        try {
            // Attempt to parse the invalid number
            int number = Integer.parseInt(invalidNumber);
            System.out.println("Parsed number: " + number);
        } catch (NumberFormatException e) {
            // Handle the exception
            System.err.println("Error: The string \"" + invalidNumber + "\" is not a valid integer.");
            System.err.println("Exception message: " + e.getMessage());
        }
    }
}

Output:

Error: The string "abc123" is not a valid integer.
Exception message: For input string: "abc123"