intermediateError Handling
Exception Handling
Handle errors gracefully with try/except/finally.
01Try / Except
Catch and handle exceptions to prevent crashes.
Python
1try:2 result = 10 / 03except ZeroDivisionError:4 print("Cannot divide by zero!")5except Exception as e:6 print(f"Unexpected error: {e}")
Output
Cannot divide by zero!
02Try / Except / Else / Finally
Else runs if no exception; finally always runs.
Python
1def safe_divide(a, b):2 try:3 result = a / b4 except ZeroDivisionError:5 print("Error: division by zero")6 return None7 except TypeError:8 print("Error: invalid types")9 return None10 else:11 print(f"Success: {result}")12 return result13 finally:14 print("Operation complete.\n")1516safe_divide(10, 3)17safe_divide(10, 0)
Output
Success: 3.3333333333333335 Operation complete. Error: division by zero Operation complete.
03Raising Exceptions
Use raise to throw exceptions intentionally.
Python
1def set_age(age):2 if age < 0:3 raise ValueError("Age cannot be negative")4 if not isinstance(age, int):5 raise TypeError("Age must be an integer")6 return age78try:9 set_age(-5)10except ValueError as e:11 print(f"Caught: {e}")
Output
Caught: Age cannot be negative