Advertisement



< Prev
Next >



Python - Try-Except-Else Block





In our last few articles, we have introduced you to exceptional handling procedures by using try-except blocks, throw statement and finally block. In this article, we are going to explain how we could associate an else block with an exception handling try-except blocks and a reason to use it.

The try-except blocks can be followed by an else block, enclosing the statements which are only going to execute when no exception is thrown by the try block.




Example of an else block with try-except blocks


An else block(if defined), will be executed only when there is no exception thrown by the try block.

#Python try-except with else statement


file = None
try:
	file = open('D:\File1.txt','w');    	#Opening a file to perform write operation
	file.write('Helloooo from Python')	#writing data to a file
	file.flush()                            #flushes the data to a file
	file.close()				#Closing the file

except Exception as e :
	print("An exception is caught :", e)

else:
    print("Code didn't throw any exception")


Output


Code didn't throw any exception




Important points to remember :


Please Subscribe

Please subscribe to our social media channels for daily updates.


Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page




Advertisement

Notifications



Please check our latest addition

PYTHON and DJANGO


Advertisement