You haven't stated whether the code is dying on all routers, or only those that are only available via telnet. If it is the latter, you might try the telnet connection first as a workaround until you get resolution on the other issue.
As another poster has suggested, it is wise to also wrap the connection code in an eval so you can "catch" the error which is occuring and handle it appropriately.