Exception Handling
Exception Handling
SI
Section
Usage Scenarios
Pros
Cons
Code examples
try:
x = 1 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print("Finally block executed")def divide(a, b):
if b == 0:
raise ValueError("Cannot divide by zero")
return a / bclass NegativeValueError(Exception):
pass
def set_age(age):
if age < 0:
raise NegativeValueError("Age cannot be negative")
return ageassert x > 0, "x must be positive"try:
x = 1 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
except TypeError:
print("Invalid data type")
Last updated