try:
stmt-1
stmt-2
stmt-3
except:
stmt-4
finally:
stmt-5
stmt-6
Case-1: If there is no exception
1, 2, 3, 5, 6 → Normal Termination
Case-2: If an exception is raised at stmt-2 and the corresponding except block is matched
1, 4, 5, 6 → Normal Termination
Case-3: If an exception is raised at stmt-2 but the corresponding except block is not matched
1, 5 → Abnormal Termination
Case-4: If an exception is raised at stmt-4, then it is always abnormal termination, but before that the finally block will be executed.
Case-5: If an exception is raised at stmt-5 or at stmt-6, then it is always abnormal termination.
Nested try–except–finally blocks:
We can take try–except–finally blocks inside try or except or finally blocks, i.e., nesting of try–except–finally is possible.
try:
--------
--------
--------
try:
--------------
--------------
--------------
except:
--------------
--------------
--------------
--------------
except:
----------
----------
----------
General Rule:
General risky code we have to take inside the outer try block and too much risky code we have to take inside the inner try block.
Inside the inner try block, if an exception is raised, then the inner except block will handle it.
Except block is responsible to handle.
If it is unable to handle, then outer except block is responsible to handle.
Eg:
try:
print("outer try block")
try:
print("Inner try block")
print(10/0)
except ZeroDivisionError:
print("Inner except block")
finally:
print("Inner finally block")
except:
print("outer except block")
finally:
print("outer finally block")
Output
outer try block
Inner try block
Inner except block
Inner finally block
outer finally block
No comments:
Post a Comment
Thank you Very Much.For Given Comment