15
Day 15: Exception Handling
Chapter 15 • Intermediate
40 min
Exception handling allows you to deal with errors gracefully instead of letting your program crash. It's like having a safety net for your code.
What are Exceptions?
Exceptions are errors that occur during program execution. They can happen for various reasons like invalid input, file not found, or division by zero.
Common Exceptions:
- ValueError - Invalid value for a function
- TypeError - Wrong data type used
- FileNotFoundError - File doesn't exist
- ZeroDivisionError - Division by zero
- IndexError - List index out of range
- KeyError - Dictionary key doesn't exist
Exception Handling:
- try - Code that might cause an error
- except - Handle specific exceptions
- else - Code that runs if no exception occurs
- finally - Code that always runs
- raise - Manually raise an exception
Benefits:
- Prevent Program Crashes - Handle errors gracefully
- Better User Experience - Show meaningful error messages
- Debugging - Easier to find and fix issues
- Robust Code - Programs that handle unexpected situations
Hands-on Examples
Exception Handling
# Basic exception handling
try:
number = int(input("Enter a number: "))
result = 10 / number
print(f"10 divided by {number} = {result}")
except ValueError:
print("Error: Please enter a valid number!")
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
except Exception as e:
print(f"An unexpected error occurred: {e}")
else:
print("Calculation completed successfully!")
finally:
print("This always runs, regardless of errors.")
# Handling multiple exceptions
def safe_divide(a, b):
try:
result = a / b
return result
except ZeroDivisionError:
return "Cannot divide by zero!"
except TypeError:
return "Please provide numbers only!"
# Test the function
print("\nTesting safe_divide function:")
print(safe_divide(10, 2))
print(safe_divide(10, 0))
print(safe_divide(10, "hello"))
# File handling with exceptions
try:
with open('nonexistent.txt', 'r') as file:
content = file.read()
except FileNotFoundError:
print("Error: File not found!")
except PermissionError:
print("Error: Permission denied!")
except Exception as e:
print(f"Unexpected error: {e}")This example shows how to handle different types of exceptions including ValueError, ZeroDivisionError, and FileNotFoundError. The finally block always executes.