Создание пользовательского исключения NumberFormatException в Java - PullRequest
5 голосов
/ 08 ноября 2011

Я пытаюсь создать свое собственное исключение 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 ]

5 голосов
/ 08 ноября 2011

как то так:

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) из SimpleDateFormat

3 голосов
/ 08 ноября 2011
try {
   // converts the month to an integer
   intmm = Integer.parseInt(mm);
} catch (NumberFormatException e) {
  throw new NumberFormatException("The month entered, " + mm+ " is invalid.");
}
1 голос
/ 08 ноября 2011

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);
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...