A ledge grab works as follows: While Mario is falling with non-positive vertical speed, the game checks if there's a wall 30 units above him and that there's no wall 150 units above him. If this passes, then it considers a point 60 units towards the wall from Mario (i.e. 10 units into the wall) and 160 units above Mario. It then checks what the highest floor is from 78 units above that point to 100 units below that point. If a floor is found, then Mario grabs the ledge.
Given these conditions, a ledge grab normally raises Mario between 30 units (inclusive) and 150 units (exclusive). However, it's possible to exploit this logic to do a glitchy ledge grab and raise Mario more than 150 units (though 238 units is the max possible raise).
Glitchy ledge grabs are rarely possible in practice due to the fact that there cannot be a wall 150 units above Mario. Fortunately, even minor deviations from perfect geometry can cause there to be no wall 150 units above Mario. For example: (1) If the wall is slightly slanted forward (2) If there are 2 walls meant to be coplanar that aren't (3) If there are 2 parallel walls with the lower one jutting out more