Dev fix trac42138

1. Add boundary check to prevent NPE.
2. Fine tune format.