Python Structuring Nested Try Except Statements
<p>I have a list of ints called companyNumbers. These are being checked against an online API to test they are valid. </p>

<p>Some company numbers have an incorrect first digit, so I would like to check the number, then if an HTTP error is received (Indicating an invalid number) to recheck the number minus its first digit. </p>

<p>If this is again invalid then the number is written to an error sheet, otherwise it is stored in correctNumbers.</p>

<pre><code>for companyNumber in companyNumbers:
    try:
        r = s.profile(companyNumber).json()
    except HTTPError:
        try:
            r = s.profile(companyNumber[1:]).json()
        except HTTPError:
            errorSheet.write(i, 0, companyNumber)
    else:
        correctNumbers.append(r)
</code></pre>

<p>I am not sure how to structure my try/except/else statements. I need the else statement to activate if either of the try blocks are successful. Currently the nested try block does not seem to do anything.</p>

<p><code>try</code> runs the code under its nest until an error occurs.  So you should put the output into that layer as well.  </p>

<pre><code>for companyNumber in companyNumbers:
    try:
        r = s.profile(companyNumber).json()
        correctNumbers.append(r)
    except HTTPError:
        try:
            r = s.profile(companyNumber[1:]).json()
            correctNumbers.append(r)
        except HTTPError:
            errorSheet.write(i, 0, companyNumber)
</code></pre>

python nested escaping try-catch