java - 在 Java 中抛出自定义 NumberFormatException

标签 java throw numberformatexception

在将字符串月份转换为整数时,我试图抛出自己的 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/

相关文章:

java - 将 Java 抛出异常替换为自定义消息并继续

java - 可以将异常存储在变量中以便稍后抛出吗?

java - 无法获取文本字段中的文本输入以解析为双倍

java - Apache Camel FOP 组件配置文件位置

java - Java ResourceBundle.getBundle 如何加载属性文件?

java - 是否可以读取可能同时写入的变量?

actionscript-3 - 在 Flash AS3 中如何放置单个 try catch 代码,以捕获整个类中的任何错误?

java - QueryForList未设置参数

java - 错误: Error during Sonar runner execution

java - 新的 BigDecimal ("0") NumberFormatException