0

I am learning Python. I have a fundamental doubt about the "try--except--else--finally" statement sequence.

As I understand if code in 'try' goes through then code in 'else' will also get executed. If that is the case, what is the need for 'else' block? Whatever code is under 'else' block can be in 'try' block itself.

Appreciate clarifications

Srinivas
  • 568
  • 1
  • 4
  • 21

2 Answers2

2

Else block gets executed when try block raises no error.
Except block gets executed when try raises an error.
finally block gets executed regardless of whether try raises an error or not

Docs about it can be found here

Achxy_
  • 1,171
  • 1
  • 5
  • 25
0

The process goes on this way:

  1. try section is executed normally
  2. if there's error (exception) raised, it goes to the except block
  3. if there's no error raised in try section, then else block will be executed
  4. then comes finally block. finally is independent of exceptions. It is executed always
  • I have found the explanation at https://stackoverflow.com/questions/855759/python-try-else – Srinivas Nov 27 '21 at 04:48
  • @Srinivas ok, I didn't know you got the answer. I had answered it 10 hours ago and you got the answer 1 hour ago –  Nov 27 '21 at 05:52