Advertisement



< Prev
Next >



Python - Try-Except-Else Block





In this tutorial, we are going to explain how we could associate an else block with an exception handling try-except block, and the reason to use it.

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




Example of an else block with try-except block


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

C#, PYTHON and DJANGO


Advertisement