简体   繁体   中英

Python: Only running exception block when try block fails

I am having trouble understanding how to write a try except block that only runs one block or the other not just half the block and then move to the exception as seen in my example f or emphasis I do not wish to run any portion of try if any line in try fails

x = 1
y = 1


try:  
    x = x+1
    print(x)
    x.append(1)
except:
    print(x)

which returns

2
2

instead of returning

1

as I would of expected. This is problematic for me because I was foolishly under the impression that only except block would be executed upon try failure. I am scraping websites using beautiful soup and my allocation of a soup usually will throw the exception and the other block will run but unforeseen errors after this allows some lists to be appended then runs the exception block and appends them again. leaving me with lists of different lengths depending on where they fall within each block.

any help is much appreciated

You could reset the computed_result to value of x in except-block on error:

x = 1
y = 1
computed_value = 0

try:  
    computed_value = x + 1
    #print(fallback_var)
    computed_value.append(1)
    print("Exceution succeed: keeping value")
except:
    print("Exceution failed: resetting value")
    computed_value = x
    #print(x)


print(computed_value)

Let's go step by step:

Your code correctly executes x=x+1 (now x is 2).

Then it correctly executes print(x) (so it prints 2).

Then it tries to execute x.append(1) (and fails)

Since it has failed to append(1) it enters the except and executes print(x) (so it prints 2)

It outputs exactly what's expected.

This run both.

Your code

try:  
    x = x+1
    print(x)
    x.append(1)
except:
    print(x)

When python start execution, it execute line by line

x = x + 1

After this x become 2 .

then

print (x)

Print 2 as first in your output.

x.append(1)

Above statment raise exception which is caught by except clause in your code.

Please remember, x value is already change to 2 in x = x + 1 statment. In except when you do

print (x)

It print 2 again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM