7

文字列の月を整数に変換するときに、独自のNumberFormatExceptionをスローしようとしています。例外をスローする方法がわかりません。どんな助けでもいただければ幸いです。コードのこの部分の前にtry-catchを追加する必要がありますか?コードの別の部分にすでに1つあります。

// 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 に答える