:
#If there is no exception
try:
statement1
statement2
statement3
except:
statement4
finally:
statement5
statement6
output:
st1,2,3,5 and 6 executed
Case 2:
try:
statement1
statement2 #exception raised here
statement3
except:
#corresponding exception block
is matched
statement4
finally:
statement5
statement6
output:
st1,4
,,5 and 6 executed and Normal termination
Case 3:
try:
statement1
statement2 #exception raised here
statement3
except:
#corresponding exception block
is not matched
statement4
finally:
statement5
statement6
output:
st1, 5
executed and Abnormal
termination
#Case 4:Exception is raised in
exception block
try:
print("statement1 ")
print("statement2 ")
print("statement3")
except
ZeroDivisionError:
print(2/0)#exception raised here
finally:
print("statement 5")
print("statement6")
"""output:
statement1
statement2
statement3
statement
5
statement6
#Case 5:Exception is raised in
finally block
try:
print("statement1 ")
print("statement2 ")
print("statement3")
except ZeroDivisionError:
print("Statement 4")
finally:
print(2/0)#exception raised here
print("statement6")
"""output:
statement1
statement2
statement3
Abnormal termination
"""
There is only two situation
where finally block is not executed i.e when exception is raised in finally
block, and os._exit(0) function.
Example:
#Case 5:finally is block is
not executed when we use ox._exit(0)
import os
try:
print("statement1 ")
print("statement2 ")
os._exit(0)
print(2/0)
except ZeroDivisionError:
print("Statement 4")
finally:
print("Statement 5")
print("statement6")
"""output:
statement1
statement2
Nested try –except-finally
blocks
"""
#Nested
try blocks
try:
print("outer try block")
try:
print("inner try block")
print(2/0) #exception raises here, and
corresponding except is matched
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
>>>
"""
We can take try-except-finally
blocks inside try or except or finally blocks it is called nesting exception
handling.
Generally risky code we have
to take inside outer try block and too much risky code we have to take inside
inner try block.
·
Inside inner try
block if an exception raised then except block is responsible to handle. If it unable to handle then outer except block
is responsible to handle.
Syntax:
try:
……
……
try:
……..
………
except:
……..
………
except:
……
……
Next: User Defined Exception
Previous:Exception Handling part 2