How to stop python script from exiting on error
<p>I wrote a small python script to do a bulk whois check of some domains using pythonwhois to do the checking. </p>

<p>The script reads domains from testdomains.txt and checks them one by one. Then it logs some information regarding the domain to results.txt</p>

<p>This is my script:</p>

<pre><code>from time import sleep
import pythonwhois

def lookup(domain):
    sleep(5)
    response = pythonwhois.get_whois(domain)
    ns = response['nameservers']
    return ns


with open("testdomains.txt") as infile:
    domainfile = open('results.txt','w')
    for domain in infile:
        ns = (lookup(domain))
        domainfile.write(domain.rstrip() + ',' + ns+'\n')
    domainfile.close()
</code></pre>

<p>My problem arises when a domain is not registered or when the whois server fails to reply for some reason. The script exits like this:</p>

<pre><code>Traceback (most recent call last):
  File "test8.py", line 17, in &lt;module&gt;
    ns = lookup(domain)
  File "test8.py", line 9, in lookup
    ns = response['nameservers']
TypeError: 'NoneType' object has no attribute '__getitem__'
</code></pre>

<p>My question is, what can I do to avoid the entire script from exiting?</p>

<p>In case of an error, I would like the script to jump to the next domain and keep running and not exit.
Logging the error to results.txt would definitely be good too.</p>

<p>Thanks!</p>

<pre><code>with open("testdomains.txt") as infile:
    domainfile = open('results.txt','w')
    for domain in infile:
        try:
            ns = (lookup(domain))
            domainfile.write(domain.rstrip() + ',' + ns+'\n')\
        except TypeError:
            pass
    domainfile.close()
</code></pre>

python