Error handling in Python using Try.. Except..
Consider the below example for your reference, you can see the TRY block followed by the EXCEPT and below that there are two additional blocks ELSE and FINALLY.
Try:
The try block will get executed first and will perform the operations given under it. If there is any exception during the operation then the try block will be stopped else the try block will completed its execution and by pass the EXCEPT block. Compulsory block
Except:
This block will get executed only if there is any exception in the try block. This Except block will handle the exception and provide a useful message to user regarding the error that has been occurred. Compulsory block
Else:
This block will be performed if there are no exception and over successful completion of the try block. This is an optional block.
Finally:
This is a final block and this block will definitely get executed even though if there is any exception and optional block in try except.
Example:
students =[
{"name":"Ram", "marks":[50,40,80]},
{"name":"Raju", "marks":[]},
{"name":"Babu", "marks":[90,80,70]}
]
try:
for student in students:
name = student["name"]
marks = student["marks"]
total = sum(marks)
average = sum(marks)/len(marks)
print(f"{name} has scored: Total={total} & Average={average}")
except Exception as e:
print("There is error in student")
print(e)
else:
print("Student list completed")
finally:
print("done")
Output:
Ram has scored: Total=170 & Average=56.666666666666664
There is error in student
division by zero
done
No comments:
Post a Comment