-1

Running the following code:

click here

I got the next output:

3 ok 6 ok oops ok ok Boom

I don't understand why does he prints the bolded ok? he doesn't even enter the loop.

I would like to get in-depth understanding of how exceptions and finally in particular works.

Thanks in advance!

  • 2
    You should not show your code in an image. It is harder to help you, as anyone trying to help you would need to write your code by hand. – Alejandro Alcalde Mar 04 '17 at 18:42
  • 3
    Not including code **in the question itself** (but only behind a link) actually satisfies the conditions for close-as-lacking-MCVE. Per the wording of the rule: *Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it **in the question itself**.* – Charles Duffy Mar 04 '17 at 18:49

2 Answers2

1

code in finally block is always executed before leaving the try-catch block. The code in finally block is executed even if an exception is caught.

For detailed explanation of exception handling in python, see python 3 documentation

Yousaf
  • 27,861
  • 6
  • 44
  • 69
0

The official spec is

If finally is present, it specifies a ‘cleanup’ handler. The try clause is executed, including any except and else clauses. If an exception occurs in any of the clauses and is not handled, the exception is temporarily saved. The finally clause is executed. If there is a saved exception it is re-raised at the end of the finally clause. If the finally clause raises another exception, the saved exception is set as the context of the new exception. If the finally clause executes a return or break statement, the saved exception is discarded:

So what happens in the fourth iteration of your loop is number is set to "a" and when you try to convert it to int an exception is raised. Since there is no matching except in the inner try block the exception is saved, the finally block is executed which gives the fourth ok output and then the saved exception is reraised and caught by the outer try block.

Paul Panzer
  • 51,835
  • 3
  • 54
  • 99