
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
except ValueError as e:
print(f"Value error: {e}")
except Exception as e:
print(f"Unexpected error: {e}")
else:
print("No error occurred")
finally:
print("This always runs")Common exceptions:
ValueError — wrong value type
TypeError — wrong data type
KeyError — dict key not found
IndexError — list index out of range
FileNotFoundError — file doesn't exist
AttributeError — object has no attribute
Raising exceptions:
def divide(a, b):
if b == 0:
raise ValueError("Denominator cannot be zero")
return a / bCustom exceptions:
class InsufficientFundsError(Exception):
passReference:
TaskLoco™ — The Sticky Note GOAT