NYC*_*uck 5 java throw numberformatexception
在将一个String月转换为整数时,我试图抛出自己的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.");*/
Run Code Online (Sandbox Code Playgroud)
这样的事情:
try {
intmm = Integer.parseInt(mm);
catch (NumberFormatException nfe) {
throw new NumberFormatException("The month entered, " + mm+ " is invalid.");
}
Run Code Online (Sandbox Code Playgroud)
或者,更好一点:
try {
intmm = Integer.parseInt(mm);
catch (NumberFormatException nfe) {
throw new IllegalArgumentException("The month entered, " + mm+ " is invalid.", nfe);
}
Run Code Online (Sandbox Code Playgroud)
编辑: 既然你已经更新了你的帖子,看起来你真正需要的是像SimpleDateFormat的parse(String)
| 归档时间: |
|
| 查看次数: |
19984 次 |
| 最近记录: |