Python’s try-except
blocks are used to catch and handle errors gracefully without crashing your program. They allow your code to continue running even when unexpected situations occur, such as dividing by zero, opening a missing file, or converting invalid input types.
In this post, we'll explore how try-except
works, different ways to use it, and real-world examples to help you write more reliable Python programs.
1. Basic Structure of try-except
try:
# code that might raise an error
except SomeError:
# code that runs if the error occurs
Example 1: Division by Zero
try:
result = 10 / 0
except ZeroDivisionError:
print("You can't divide by zero!")
This prevents your program from crashing and displays a custom error message.
2. Catching Specific Exceptions
try:
number = int("abc")
except ValueError:
print("Please enter a valid number.")
This handles only ValueError
and lets other errors raise normally.
3. Catching Multiple Exceptions
Example 2: Handling More Than One Error Type
try:
x = int("abc")
y = 10 / 0
except ValueError:
print("Conversion error.")
except ZeroDivisionError:
print("Math error.")
4. Using a Generic Exception
Handler
When you're unsure what error might occur, catch all exceptions using Exception
.
Example 3: Generic Catch
try:
risky_code = open("missing.txt")
except Exception as e:
print("Something went wrong:", e)
Note: Use this sparingly. It can mask real issues during debugging.
5. try-except-else
Structure
else
runs only if no exceptions were raised in the try
block.
Example 4:
try:
value = int("123")
except ValueError:
print("Invalid number.")
else:
print("Conversion successful:", value)
6. try-except-finally
Structure
finally
always runs, whether or not there was an exception.
Example 5:
try:
file = open("example.txt", "r")
except FileNotFoundError:
print("File not found.")
finally:
print("This block always runs.")
7. Nesting Try-Except Blocks
Example 6: Handling Errors at Different Levels
try:
number = int(input("Enter a number: "))
try:
result = 100 / number
except ZeroDivisionError:
print("Can't divide by zero.")
except ValueError:
print("Invalid input.")
8. Raising Custom Errors with Try-Except
Example 7:
try:
age = -5
if age < 0:
raise ValueError("Age cannot be negative.")
except ValueError as ve:
print("Error:", ve)
9. Summary Table
Block | Purpose |
---|---|
try |
Contains code that might raise an exception |
except |
Handles specific or general exceptions |
else |
Runs only if no exception is raised |
finally |
Always runs, often used for cleanup |
10. Final Thoughts
The try-except
block is a powerful tool that lets you handle runtime errors without crashing your program. By using it properly, you can build applications that are more stable, user-friendly, and easier to debug. Always handle known exceptions specifically, and reserve generic exception handling for unknown or unexpected errors.