Throwing a custom NumberFormatException in Java

I am trying to throw my own NumberFormatException when I enter a String in Integer. Not sure how to throw an exception. Any help would be greatly appreciated. Should I add try-catch before this piece of code? I already have one in another part of my code.

// 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
source share
3 answers

something like that:

 try { intmm = Integer.parseInt(mm); catch (NumberFormatException nfe) { throw new NumberFormatException("The month entered, " + mm+ " is invalid."); } 

Or, a little better:

 try { intmm = Integer.parseInt(mm); catch (NumberFormatException nfe) { throw new IllegalArgumentException("The month entered, " + mm+ " is invalid.", nfe); } 

EDIT: Now that you have updated your post, it seems like you really need something like parse (String) SimpleDateFormat

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

Integer.parseInt () already throws a NumberFormatException. In your example, it seems more appropriate to throw an 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); } 
+1
source

Source: https://habr.com/ru/post/1380219/


All Articles