I don't understand "move your code in that method".
The exception should not happen any more since the invocation of getToAddress() is now guarded by checking the type of script.