Try-Except Error Handling
Handle errors gracefully with Python exception handling.
Errors happen in every program. Maybe a file does not exist, a user enters invalid input, or a network request fails. Exception handling with try-except lets your program respond to errors gracefully instead of crashing. This is a critical skill for building robust, production-ready applications.
📚 Concepts & Theory
Basic Try-Except
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
Catching Multiple Exceptions
try:
value = int(input("Enter a number: "))
result = 10 / value
except ValueError:
print("That is not a valid number")
except ZeroDivisionError:
print("Cannot divide by zero")
The else Clause
Runs if no exception occurred:
try:
number = int("42")
except ValueError:
print("Invalid number")
else:
print(f"Success! Got {number}")
The finally Clause
Always runs, even if an exception occurred:
try:
file = open("data.txt")
data = file.read()
except FileNotFoundError:
print("File not found")
finally:
file.close() # Always close the file
Catching Any Exception
try:
risky_operation()
except Exception as e:
print(f"Error: {e}") 🎯 Your Challenge
Write code that tries to convert the string "hello" to an integer using int(). Catch the ValueError and set a variable `result` to 0 if the conversion fails. If it succeeds, set `result` to the converted value.
📝 Starter Code
# Try to convert "hello" to integer
text = "hello"
try:
result =
except ValueError:
result =
- Put the risky operation inside try
- ValueError is raised for invalid conversions
- The except block only runs if an error occurs
- Set your fallback value in the except block
Solution
text = "hello"
try:
result = int(text)
except ValueError:
result = 0
Explanation
We try to convert "hello" to an integer with int(text). Since "hello" is not a valid number, Python raises a ValueError. The except block catches this error and sets result to 0 as a fallback.
⚠️ Common Mistakes to Avoid
- Catching too broad exceptions (bare except)
- Not handling specific exception types
- Putting too much code in the try block
- Forgetting that except runs only if an exception occurs