Improve helper function

Make faster by throwing exception earlier