Advertisement
#Python- finally block example
try:
print("Hello from DecodeJava")
except Exception as e:
print( "Exception caught : ", e)
finally:
print("A finally block executes with or without exception")
Hello from DecodeJava
A finally block executes with or without exception
# Python - finally block example
import sys
try:
i = 'one'
ab = i + 2
except Exception as e:
print("Exception caught - ",e)
print(sys.exc_info()) # This function gives the name of caught exception which was thrown by try block
finally:
print("A finally block executes with or without exception")
Exception caught - can only concatenate str (not "int") to str
(<class 'TypeError'>, TypeError('can only concatenate str (not "int") to str'), <traceback object at 0x0000000002EF83C8>)
A finally block executes with or without exception
# Python - finally block example
import sys
try:
i
except TypeError as e:
print("Exception caught - ",e)
finally:
print("A finally block executes with or without exception")
A finally block executes with or without exception
Traceback (most recent call last):
File "C:\Users\RadheKrishna\Desktop\Python Programs\exp9.py", line 7, in <module>
i
NameError: name 'i' is not defined
Advertisement
# Python - finally block example
import sys
try:
fruits = ["Apple", "Pineapple", "Orange"] # Defining an array with three elements
print(fruits[5]) #Accessing an invalid index of array i.e 5
finally:
print("A finally block executes with or without exception")
A finally block executes with or without exception
Traceback (most recent call last):
File "C:/Users/RadheKrishna/Desktop/Python Programs/exp10.py", line 8, in
print(fruits[5])
IndexError: list index out of range
# Python - finally block example
try :
print("Hello there. Have a happy life! ")
finally:
print("A finally block executes with or without exception")
Hello there. Have a happy life!
A finally block executes with or without exception
# Python - finally block example
#Declaring a variable named File with None keyword to temporarily not give it a value
file = None
try:
file = open('D:\File.txt','w'); #creating a file
file.write('Hello from Python') #writing data to a file
file.flush() #flushes the data to a file
except Exception as e :
print("An exception is caught :", e)
finally :
file.close() #cleaning up the resources i.e. closing an opened file.
Advertisement
Advertisement
Please check our latest addition
C#, PYTHON and DJANGO
Advertisement