Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialjinhwa yoo
10,042 Pointshelp me///
I knew how to structure "try ~ catch" but ... what kind of statement I have to put it??
1 Answer
Steve Hunter
57,712 PointsHi Jinhwa,
You aren't using a try/catch here - you're throwing the exception (it'll be caught elsewhere). You have two things to test; the first character is a lowercase 'm' and the second character is capitalised. So, IF those two things are true, return the fieldName
ELSE throw the exception.
My code came out something like this:
public static String validatedFieldName(String fieldName) {
if(fieldName.charAt(0) == 'm' && Character.isUpperCase(fieldName.charAt(1))) {
// both things are true - do whatever success looks like
return fieldName;
} else {
throw new IllegalArgumentException("This does not meet the requirements!");
}
// you could put the return line here
}
Although there are other ways of structuring this. The return
statement can be outside of the if
statement. If the true part is called, where the return
is now, that means the else
won't run. The tests are binary & mutually exclusive. So, the return
can be after the if
statement. You could negate both tests and have no else
clause, perhaps! There are different solutions to this.
I hope that helps.
Steve.