Errors (exceptions) happen in every program. Python's try and except blocks let you handle them gracefully instead of crashing.
Why handle errors?
Without handling, an error stops the program.
number = int(input("Enter a number: "))
print(10 / number)
If the user enters "zero" or "hello", the program crashes.
With error handling, you can recover or show a friendly message.
The basic try-except structure
try:
number = int(input("Enter a number: "))
result = 10 / number
print(result)
except:
print("Something went wrong. Please enter a valid number.")
The code in try runs normally.
If an error occurs, Python jumps to except instead of crashing.
Handling specific errors
It is better to catch specific exceptions.
Common ones:
-
ValueError: wrong type (e.g., int("hello")) -
ZeroDivisionError: division by zero -
IndexError: list index out of range -
KeyError: dictionary key not found
try:
age = int(input("Enter your age: "))
print(100 / age)
except ValueError:
print("Please enter a valid number.")
except ZeroDivisionError:
print("Age cannot be zero.")
Using else and finally
-
else: runs only if no error occurred -
finally: runs always (error or not)
try:
file = open("data.txt")
content = file.read()
except FileNotFoundError:
print("File not found.")
else:
print("File read successfully.")
file.close()
finally:
print("Operation complete.")
Simple examples
Safe division:
try:
num = float(input("Enter numerator: "))
den = float(input("Enter denominator: "))
result = num / den
except ZeroDivisionError:
print("Cannot divide by zero.")
except ValueError:
print("Please enter numbers only.")
else:
print(f"Result: {result}")
Safe list access:
scores = [85, 92, 78]
try:
index = int(input("Enter index: "))
print(scores[index])
except IndexError:
print("Index out of range.")
except ValueError:
print("Please enter a number.")
Important notes
- Be specific with exceptions when possible.
- Avoid bare
except:in real programs (it catches everything, including system exits). - Use
finallyfor cleanup (closing files, connections).
Quick summary
- Put risky code in
try. - Catch errors with
except(specific types when possible). - Use
elsefor code that runs only on success. - Use
finallyfor cleanup. - Handling errors makes programs more robust.
Practice adding try-except to small scripts. Error handling is essential for reliable Python programs.
Top comments (0)