Lesson 12.2: try / except / finally
What you will learn:
- How to use
try/exceptto catch errors - Catching specific exception types
- Using multiple
exceptblocks - The
elseandfinallyclauses - Raising your own exceptions
1. Basic try/except
Instead of letting errors crash your program, you can catch them and handle them gracefully:
Without Error Handling (Crashes)
age = input("Enter your age: ") # User types "twenty" age = int(age) # ValueError! Program crashes print(f"You are {age} years old")
With Error Handling (Graceful)
try: age = input("Enter your age: ") age = int(age) print(f"You are {age} years old") except: print("Please enter a valid number.")
Enter your age: twenty
Please enter a valid number.
Please enter a valid number.
How it works: Python tries to run the code in the
try block. If an error occurs, it jumps to the except block instead of crashing. If no error occurs, the except block is skipped.
2. Catching Specific Exceptions
It is best practice to catch specific exception types rather than catching everything:
Catching Specific Errors
try: number = int(input("Enter a number: ")) result = 100 / number print(f"100 / {number} = {result}") except ValueError: print("That's not a valid number!") except ZeroDivisionError: print("You can't divide by zero!")
Getting the Error Message
try: file = open("missing.txt", "r") except FileNotFoundError as e: print(f"Error: {e}")
Error: [Errno 2] No such file or directory: 'missing.txt'
3. The else Clause
The else block runs only if no error occurred in the try block:
Using else
try: number = int(input("Enter a number: ")) except ValueError: print("Invalid input!") else: # Only runs if no error occurred print(f"You entered: {number}") print(f"Doubled: {number * 2}")
4. The finally Clause
The finally block runs no matter what - whether an error occurred or not. It is useful for cleanup tasks:
Using finally
try: file = open("data.txt", "r") content = file.read() print(content) except FileNotFoundError: print("File not found!") finally: print("Finished file operation.") # This always runs
Complete try/except/else/finally
try: value = int(input("Enter a number: ")) except ValueError: print("Not a valid number!") else: print(f"Success! You entered {value}") finally: print("Program complete.") # Order: try → except (if error) OR else (if no error) → finally (always)
5. Raising Exceptions
You can raise your own exceptions using the raise keyword:
Raising Exceptions
def set_age(age): if age < 0: raise ValueError("Age cannot be negative") if age > 150: raise ValueError("Age seems unrealistic") return age try: my_age = set_age(-5) except ValueError as e: print(f"Invalid age: {e}")
Invalid age: Age cannot be negative
6. Practical Example: Safe User Input
Input Validation Loop
def get_positive_number(): while True: try: num = float(input("Enter a positive number: ")) if num <= 0: print("Number must be positive!") else: return num except ValueError: print("That's not a valid number. Try again.") result = get_positive_number() print(f"You entered: {result}")
Enter a positive number: abc
That's not a valid number. Try again.
Enter a positive number: -3
Number must be positive!
Enter a positive number: 42
You entered: 42.0
That's not a valid number. Try again.
Enter a positive number: -3
Number must be positive!
Enter a positive number: 42
You entered: 42.0
Check Your Understanding
In a try/except/else/finally block, when does the else block run?
The else block runs only when no exception occurred in the try block. If an error happens and the except block runs, the else block is skipped. The finally block, however, always runs regardless.
Key Takeaways
try/exceptcatches errors and prevents program crashes- Always catch specific exception types when possible
- Use
as eto capture the error message elseruns only if no error occurredfinallyalways runs, regardless of errors- Use
raiseto create your own exceptions for invalid data - Combine
try/exceptwith awhileloop for input validation