Exception Handling In Python
Concept
When an error occurs, or exception as we call it, Python will normally stop and generate an error message
But this is not expected in Real Life Application, So these exceptions can be handled using the try, except
statement.
Code Example
As we all know, 0/n = 0 and n/0 = ∞
Example 1:
try:
result = 0/10
print("All Good")
except Exception as e:
result = 0
print("An exception occurred : ", e)
else:
print("No Exception Occurred")
finally:
print("Result is : ", result)
Output:
All Good
No Exception Occurred
Result is : 0
Example 2:
try:
result = 0/10
print("All Good")
except Exception as e:
result = 0
print("An exception occurred : ", e)
else:
print("No Exception Occurred")
finally:
print("Result is : ", result)
Output:
An exception occurred : division by zero
Result is : 0
Note**: If try executed successfully then only else block will be executed but if not then except block will be executed, Finally will execute definitely. Finally has no dependency on try or except or else.
Custom Exception Display
Example 3:
x = 10
if x == 10:
raise ValueError
elif x == 20:
raise KeyboardInterrupt
elif x == 30:
raise Exception("My Choice")
else:
print("All Okay")
Output:
Traceback (most recent call last): File "./prog.py", line 4, in ValueError
Comments
Post a Comment