An important note is that the error is being caused by the fact that you are trying to get characters between 0 and 3. But
0 - "r",
1 - "a",
2 - "j",
3 - There's no character here, but you're trying to access it, so an exception is thrown.
You're putting your try/catch in the wrong place.
Checking the length of the string first (better)
To get the length of a string, one can access its .length()
method, which takes no arguments. If it's greater than 3, execute the code, but otherwise don't.
if(currentUserFirstName.length() > 3) {
// your substring code
// then your for loop
} else {
// error handling
}
This is probably cleaner, since silencing an exception isn't always a good idea.
Using a try/catch statement (worse)
This is what you attempted to do in your question. Just move it up a little bit, around the substring attempt.
try{
String strFoo[] = new String[]{
(currentUserLastName.substring(0, 3)+"."+currentUserFirstName),
(currentUserFirstName+"."+currentUserLastName.substring(0, 1))
};
/* then either
a) put your for-loop here
b) mark a variable as true here, and check after the entire try/catch to see if you should run the loop
neither is good. Best use the If/Else approach
*/
} catch(Exception e) {
System.out.println("Exception");
}
This will work, but resorting to try/catch isn't needed in this case, and using one anyway could mean that if you have another error in the same piece of code, it'll be silently hidden and your code will react as if you're substring is out of range.
Since your for-loop at the end relies on everything succeeding, you have to make sure nothing failed before continuing. The best way to do this would be switching to the if/else method (and putting your for-loop in the "if" part). If you don't want to do this, you can either put your code in the "try" section (but if you have some other problem in your for-loop, your code will assume it's because of the substring problem); or mark a variable as true
, or false
, depending on whether the code entered the catch
phase, and then put your for-loop in an if-statement, but this is, again sloppy.
The best way, in my opinion, is, as I mentioned, using the if/else approach. It's very rarely clean code to use a try/catch to handle these issues.