Error Handling and Exceptions
Duration: 5 min
Errors happen. Good programs handle them gracefully instead of crashing. Python uses exceptions for error handling.
Learn more: https://docs.python.org/3/tutorial/
Try-Except Blocks
# Basic try-except
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
# Multiple exceptions
try:
num = int("abc")
except ValueError:
print("Invalid number format")
except TypeError:
print("Type error")
# Catch all exceptions (not recommended)
try:
result = 10 / 0
except Exception as e:
print(f"Error: {e}")
# Try-except-else-finally
try:
num = int("42")
except ValueError:
print("Invalid input")
else:
print(f"Number is {num}")
finally:
print("This always runs")Cannot divide by zero!
Invalid number format
Error: division by zero
Number is 42
This always runsRaising Exceptions
# Raise built-in exception
def validate_age(age):
if age < 0:
raise ValueError("Age cannot be negative")
return age
try:
validate_age(-5)
except ValueError as e:
print(f"Error: {e}")
# Custom exception
class InsufficientFundsError(Exception):
pass
def withdraw(balance, amount):
if amount > balance:
raise InsufficientFundsError("Not enough money")
return balance - amount
try:
withdraw(100, 150)
except InsufficientFundsError as e:
print(f"Error: {e}")Error: Age cannot be negative
Error: Not enough money💡 Tip: Use specific exceptions, not generic 'Exception'. This makes debugging easier.
❓ What does 'finally' block do?
# Advanced example for Error Handling and Exceptions
# Production-ready pattern
print('Advanced implementation')Advanced implementation❓ What is a best practice when working with Error Handling and Exceptions?
💡 Tip: Pro Tip: Master Error Handling and Exceptions thoroughly before moving to advanced topics. This foundation is crucial for writing professional Python code.