java.lang.NumberFormatException
是 Java 中常见的运行时异常,当应用程序尝试将字符串转换为数值类型(如 int
、double
等)但字符串格式不正确时,就会抛出此异常。以下是关于这个异常的基础概念、原因、解决方法以及相关应用场景的详细解释。
NumberFormatException
属于 java.lang.RuntimeException
的子类,表示在数字格式转换过程中发生了错误。这种异常通常发生在使用 Integer.parseInt()
、Double.parseDouble()
等方法时,如果传入的字符串不能被正确解析为相应的数值类型。
Integer.parseInt("")
或 Double.parseDouble(" ")
。Integer.parseInt("abc")
或 Double.parseDouble("12.3a")
。int
类型。try-catch
语句来捕获并处理 NumberFormatException
。try-catch
语句来捕获并处理 NumberFormatException
。以下是一个完整的示例,展示了如何安全地进行字符串到整数的转换:
public class NumberFormatExample {
public static void main(String[] args) {
String[] inputs = {"123", " 456 ", "abc", "", "789xyz"};
for (String input : inputs) {
try {
int number = parseInteger(input);
System.out.println("Parsed number: " + number);
} catch (NumberFormatException e) {
System.err.println("Failed to parse '" + input + "': " + e.getMessage());
}
}
}
public static int parseInteger(String input) throws NumberFormatException {
input = input.trim();
if (input.isEmpty()) {
throw new NumberFormatException("Input string is empty or contains only whitespace.");
}
return Integer.parseInt(input);
}
}
通过这种方式,可以有效地避免和处理 NumberFormatException
,确保程序的健壮性和可靠性。
领取专属 10元无门槛券
手把手带您无忧上云