Error Handling in Python
try / except
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
except (TypeError, ValueError) as e:
print(f"Type/Value error: {e}")
except Exception as e:
print(f"Unexpected: {e}")
else:
print("No error occurred")
finally:
print("Always runs")Raising Exceptions
def divide(a, b):
if b == 0:
raise ValueError("Divisor cannot be zero")
return a / bCustom Exceptions
class AppError(Exception):
pass
raise AppError("Something went wrong")