×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
1
Language: Python
Posted by: Jean-Pierre Hermans
Added: May 23, 2021 8:41 AM
Views: 3927
Tags: no tags
  1. # Example 1
  2. try:  
  3.     a = int(input("Enter a:"))    
  4.     b = int(input("Enter b:"))    
  5.     c = a/b  
  6.     print(c)
  7. except:  
  8.     print("Can't divide with zero")
  9.    
  10. # Example 2
  11. try:    
  12.     #this will throw an exception if the file doesn't exist.    
  13.     fileptr = open("file.txt","r")    
  14. except IOError:    
  15.     print("File not found")    
  16. else:    
  17.     print("The file opened successfully")    
  18.     fileptr.close()  
  19.  
  20. # Example 3
  21. try:
  22.   fptr = open("data.txt",'r')
  23.   try:
  24.     fptr.write("Hello World!")
  25.   finally:
  26.     fptr.close()
  27.     print("File Closed")
  28. except:
  29.   print("Error")
  30.  
Comments disabled