Python Full Tutorial — Part 9

Real programs fail. Strong programs handle failure gracefully.

Error handling is what separates beginners from professionals.

1. What is an Error?

An error is a problem that stops program execution.

Example Error

print(10 / 0)
  

This causes a ZeroDivisionError.

2. Why Error Handling Matters

3. try & except

Basic Error Handling

try:
    print(10 / 0)
except:
    print("Something went wrong")
  

4. Catching Specific Errors

Specific Exception

try:
    x = int("abc")
except ValueError:
    print("Invalid number")
  

5. Multiple except Blocks

Multiple Errors

try:
    a = int(input("Enter number: "))
    print(10 / a)
except ValueError:
    print("Please enter a valid number")
except ZeroDivisionError:
    print("Cannot divide by zero")
  

6. else Block

Runs only if no error occurs.

else Example

try:
    num = int(input("Enter number: "))
except ValueError:
    print("Invalid input")
else:
    print("You entered:", num)
  

7. finally Block

Always runs — error or no error.

finally Example

try:
    file = open("data.txt", "r")
    print(file.read())
except FileNotFoundError:
    print("File not found")
finally:
    print("Program finished")
  

8. Real-World Example: Safe Calculator

Calculator with Error Handling

def divide(a, b):
    try:
        return a / b
    except ZeroDivisionError:
        return "Cannot divide by zero"

print(divide(10, 2))
print(divide(10, 0))
  

9. Raising Your Own Errors

raise Keyword

age = -5

if age < 0:
    raise ValueError("Age cannot be negative")
  

10. Common Mistakes

Key Takeaway

Error handling is not about avoiding errors. It is about controlling failures.

Next part: Modules & Packages.

Disclaimer:
This tutorial is for educational purposes only. Always handle errors explicitly in production systems.