Error Handling in Python
Like Java and C++, python also offers a way to handle exceptions using try, except, and finally block.
Python: 3.0    Abhay Parashar    04 Jul 2021   0
Login to upvote
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# Example 1
try:  
    a = int(input("Enter a:"))    
    b = int(input("Enter b:"))    
    c = a/b  
    print(c)
except:  
    print("Can't divide with zero") 
    
# Example 2
try:    
    #this will throw an exception if the file doesn't exist.     
    fileptr = open("file.txt","r")    
except IOError:    
    print("File not found")    
else:    
    print("The file opened successfully")    
    fileptr.close()  

# Example 3
try:
  fptr = open("data.txt",'r')
  try:
    fptr.write("Hello World!")
  finally:
    fptr.close()
    print("File Closed")
except:
  print("Error")
Copy | Download as: .py file   PNG
Share on: FB   Twitter   LinkedIn   WA
©2021 - code108labs   Contributors   Hosted on DigitalOcean   Partner website: pythoncircle.com