You are currently viewing NumberFormatException in Java

NumberFormatException in Java

  • Post author:
  • Post category:Java
  • Post comments:0 Comments
  • Post last modified:July 30, 2024

What is NumberFormatException?

NumberFormatException is a subclass of RuntimeException in Java. It’s thrown to indicate that the application has attempted to convert a string to one of the numeric types (such as Integer, Float, Double, etc.), but the string doesn’t have the appropriate format.

Causes of NumberFormatException

  1. Parsing Non-Numeric Characters: When trying to parse a string containing characters other than numeric digits.
  2. Empty or Null Strings: When attempting to parse an empty or null string.
  3. Overflow or Underflow: When the parsed number is larger or smaller than the maximum or minimum value of the target data type.
  4. Incorrect Format: When the string representation doesn’t match the expected format for the data type.

Handling NumberFormatException

To handle NumberFormatException, you can use exception handling techniques such as try-catch blocks.

Example 1: Parsing Integers

public class NumberFormatExceptionExample {
    public static void main(String[] args) {
        String str = "abc";
        try {
            int num = Integer.parseInt(str);
            System.out.println("Parsed number: " + num);
        } catch (NumberFormatException e) {
            System.out.println("NumberFormatException caught: " + e.getMessage());
        }
    }
}

Output:

NumberFormatException caught: For input string: "abc"

Example 2: Parsing Doubles

public class NumberFormatExceptionExample {
    public static void main(String[] args) {
        String str = "3.14abc";
        try {
            double num = Double.parseDouble(str);
            System.out.println("Parsed number: " + num);
        } catch (NumberFormatException e) {
            System.out.println("NumberFormatException caught: " + e.getMessage());
        }
    }
}

Output:

NumberFormatException caught: For input string: "3.14abc"

Example 3: Handling Empty Strings

public class NumberFormatExceptionExample {
    public static void main(String[] args) {
        String str = "";
        try {
            int num = Integer.parseInt(str);
            System.out.println("Parsed number: " + num);
        } catch (NumberFormatException e) {
            System.out.println("NumberFormatException caught: " + e.getMessage());
        }
    }
}

Output:

NumberFormatException caught: For input string: ""

Conclusion

NumberFormatException is a common exception encountered when working with numeric conversions in Java. Handling it properly ensures robustness in your applications when dealing with user input or external data sources. Always wrap your parsing code with appropriate exception handling to gracefully handle invalid input.

Leave a Reply