擅长:python、mysql、java
<p>首先,如果你对IO错误无能为力,不要通过返回-1来掩盖它(“1是什么意思?为什么我没有得到一个主机名回来?”)。只需记录<code>get_hostname</code>可能引发IOError</p>
<pre><code>def get_hostname(ifname):
# Do stuff that might raise an IOError
return hostname
</code></pre>
<p>递归版本也是如此。返回有效的主机名,或者引发异常(或者让未捕获的异常继续)</p>
<pre><code>def get_hostname_r(lst):
if not lst:
raise IOError("Hostname not found")
try:
hostname = get_hostname(lst[0])
print >>sys.stderr, 'Found {0}'.format(hostname)
return hostname
except IOError:
print 'Not found with {0}'.format(lst[0])
return get_hostname_r(lst[1:])
</code></pre>
<p>当然,递归并不是最好的编写方法;使用一个简单的<code>for</code>循环来迭代<code>lst</code></p>
<pre><code>def get_hostname_iter(lst):
for ifname in lst:
try:
return get_hostname(ifname)
except IOError:
continue
raise IOError("Hostname not found")
</code></pre>