Pythonic way to write many try/except clauses?
<p>I am writing a script to write ~200 cells of somewhat unique data to an excel spreadsheet. My code is following this basic pattern:</p>

<pre><code>try:
    sheet.cell(row=9, column=7).value = getData()
except:
    sheet.cell(row=9, column=7).value = 'NA'
</code></pre>

<p>Basically if there is an error then write some placeholder to the cell. I was wondering if there is a shorter, more pythonic way to write this than having 200 of these in sequence.</p>

<p>Put all your cells into a list, or better, get column/row from nested <code>for i in xrange()</code> loops so that you can write one line of code to perform on all of them.</p>

<pre><code>for r in xrange(0, 10):
    for c in xrange(0, 10):
        try:
            sheet(row=r, column=c).value = getData()
        except BadDataException:
            sheet(row=r, column=c).value = 'NA'
</code></pre>

<p>But as others have mentioned, if you can change getData, have it return the default (or None) instead of raising an Exception. If you can't change getData, check the documentation to see if it has a <code>default</code> option of some kind, like many Python objects (e.g., dictionaries with <code>.get()</code>)</p>

<p><em>UPDATE</em>: Or, see Zakhar's answer to wrap getData if you can't change it yourself.</p>

python excel