Reputation: 169
I learnt about using the except function to prevent your code from crashing but I want to understand it better on how python executes it.
For example, I have code that adds a pair of numbers and if the variable nums has more than two numbers it should give AssertionError.
1 def sum_pair(pair):
2 assert len(pair) == 2
3 return pair[0] + pair[1]
4 try:
5 total = sum_pair(nums)
6 print 'The total is', total
7 except AssertionError:
8 print 'Abort'
So from my view python executes Lines 1, 2, 4, 5, 7 and 8 only. Is this correct way to understand it?
Thank you
Upvotes: 0
Views: 44
Reputation: 781741
When an exception is signalled, the call stack is searched for a try
block that has an except
clause that matches the type of the exception. The stack is unwound to that point, the code in the except
clause is executed, and then execution continues after the try
block.
So when line 2 detects that the assertion has failed, it immediately exits the sum_pair()
function and executes the code starting from line 8.
Upvotes: 2