gpt4 book ai didi

java - 在 Java 中抛出自定义 NumberFormatException

转载 作者:搜寻专家 更新时间:2023-10-31 19:34:55 24 4
gpt4 key购买 nike

在将字符串月份转换为整数时,我试图抛出自己的 NumberFormatException。不确定如何抛出异常。任何帮助,将不胜感激。我需要在这部分代码之前添加一个try-catch吗?我的代码的另一部分已经有一个。

// sets the month as a string
mm = date.substring(0, (date.indexOf("/")));
// sets the day as a string
dd = date.substring((date.indexOf("/")) + 1, (date.lastIndexOf("/")));
// sets the year as a string
yyyy= date.substring((date.lastIndexOf("/"))+1, (date.length()));
// converts the month to an integer
intmm = Integer.parseInt(mm);
/*throw new NumberFormatException("The month entered, " + mm+ is invalid.");*/
// converts the day to an integer
intdd = Integer.parseInt(dd);
/* throw new NumberFormatException("The day entered, " + dd + " is invalid.");*/
// converts the year to an integer
intyyyy = Integer.parseInt(yyyy);
/*throw new NumberFormatException("The yearentered, " + yyyy + " is invalid.");*/

最佳答案

像这样:

try {
intmm = Integer.parseInt(mm);
catch (NumberFormatException nfe) {
throw new NumberFormatException("The month entered, " + mm+ " is invalid.");
}

或者,更好一点:

try {
intmm = Integer.parseInt(mm);
catch (NumberFormatException nfe) {
throw new IllegalArgumentException("The month entered, " + mm+ " is invalid.", nfe);
}

编辑:既然您已经更新了帖子,您实际上似乎需要的是类似parse(String) 的东西。简单日期格式

关于java - 在 Java 中抛出自定义 NumberFormatException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8052941/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com