There is no inconsistency in the code. Since n defined outside the try block, it is in scope during the execution of the except block.
In addition, you handle the interrupt and continue the loop without any additional errors. Thus, the flow of the program also continues.
If you want your code to be interrupted, you must throw an interrupt and force those who call your function to catch it. If you want the return value to mean an error, you need to encode it in your domain (for example, if n represents the number of non-zeros received, you can return a negative number if an exception occurs).
source share