I'm trying to find a way to check if a substring causes an out of bounds error in an If statement

This is what I have got so far but if the original string has less than 8 characters after substring then I will get an error.

String s = 'This is M-000034'; // if this was M-0023 it will cause error
Boolean replied = false;
String subs = 'M-';

String s1 = s.toUpperCase();
String s2 = s1.deleteWhitespace();
replied = true;
Integer r = s2.indexOf(subs);
String caseNumber = s2.substring(r, r+8);

}else {

Thanks in advance!


1 Answer 1


This is a classic bounds-overflow bug. Before you take a fixed-length substring or request a specific string index, you must check whether the string contains enough characters to respond to the request.

In this case, you can either use the one-argument version of String.substring(), which starts at the specified index and goes to the end of the string, or you can do some simple arithmetic with a ternary expression:

String caseNumber = s2.substring(r, r+8 > s2.length() ? s2.length() : r+8);

The ternary operator (?:) is the only three-argument operator in Apex and most other C/Java family languages. Basically it works like this:

<boolean expresssion> ? <true value> : <false value>

It evaluates the boolean expression and then returns either the true value or the false value as appropriate. It's a terse, expression-based form of an if conditional. Here, we use it to check if the string is too short to take r+8 characters. If it is, we just go to the end of the string; otherwise, we take r+8 characters.

  • Thanks it works! not quite understanding what's happening after r+8..
    – ridwan
    May 28, 2018 at 15:02
  • Added a little more explanation on the ternary operator.
    – David Reed
    May 28, 2018 at 15:04

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .