The exception is pushed from Script.getToAddress() method.
I think it's better to move your code in that method.