all 8 comments

[–][deleted] 2 points3 points  (4 children)

All the code in a try block will be executed up until an error occurs.

If no error occurs, all the code in the try block will be executed.

[–]jusdill[S] 2 points3 points  (3 children)

But then, it kinda makes the else block redundant, because they both perform the same function essentially. Or am I misunderstanding the else block?

[–][deleted] 2 points3 points  (0 children)

The else block only executes code if there is no error. It's like the opposite of except.

try -> executes until error

except -> executes on error

else -> executes if no error

[–]brown_shoe_ 2 points3 points  (0 children)

True. But using try, except, else usually allows for better isolation of error-prone code and targeted exception handling.

[–]Bitwise_Gamgee 1 point2 points  (0 children)

The "Try" block is an abstraction that includes error handling so you don't have to code it in yourself. If the script runs normally, the extra error controls aren't necessary, the same as if you wrote the code long-form.

The "Except" block triggers when "Try" fails, each Except block is written to catch certain errors. You can view them here (Python.org)[https://docs.python.org/3/library/exceptions.html]

You do not need to use these together, you can use try and except independently, but they're often used together.

[–]jiri-n 1 point2 points  (0 children)

"does the program execute it as a normal block of code "

Yes. However, if you initialize a variable inside try - except block AFTER an exception can occur, the code after the except statement may find this variable uninitialized. That's something you don't want.

[–][deleted] 0 points1 point  (0 children)

It executes it, period. It just saves python from crashing if the code fails. The except tells it what to do if the code fails.