在Java中抛出自定义NumberFormatException

时间:2011-11-08 15:34:50

标签: java throw numberformatexception

我想在将一个String月转换为Integer时抛出自己的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.");*/

3 个答案:

答案 0 :(得分:5)

类似的东西:

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)

答案 1 :(得分:3)

try {
   // converts the month to an integer
   intmm = Integer.parseInt(mm);
} catch (NumberFormatException e) {
  throw new NumberFormatException("The month entered, " + mm+ " is invalid.");
}

答案 2 :(得分: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);
}