7

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

3 回答 3

6

像这样的东西:

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);
}

编辑: 现在你已经更新了你的帖子,看起来你真正需要的是SimpleDateFormat 的parse(String)

于 2011-11-08T15:38:38.657 回答
3
try {
   // converts the month to an integer
   intmm = Integer.parseInt(mm);
} catch (NumberFormatException e) {
  throw new NumberFormatException("The month entered, " + mm+ " is invalid.");
}
于 2011-11-08T15:37:57.593 回答
1

Integer.parseInt() 已经产生 NumberFormatException。在您的示例中,抛出 IllegalArgumentException 似乎更合适:

int minMonth = 0;
int maxMonth = 11;
try 
{
    intmm = Integer.parseInt(mm);
    if (intmm < minMonth || intmm > maxMonth) 
    {
      throw new IllegalArgumentException
      (String.format("The month '%d' is outside %d-%d range.",intmm,minMonth,maxMonth));
    }
}
catch (NumberFormatException nfe) 
{
  throw new IllegalArgumentException
  (String.format("The month '%s'is invalid.",mm) nfe);
}
于 2011-11-08T15:51:33.040 回答