Thuta Learning
ရှာဖွေရန်
IntermediateProgrammingbeginner

Try...Except (Enhanced)

စိတ်လျှော့ပါ။ ဒီခန်းကို စာအုပ်လိုမဟုတ်ဘဲ စကားပြောသလိုပဲ၊ နားလည်လွယ်အောင် ရှင်းပါမယ်။

Python Error Handling Visual Guide
try, except, else, finally flow ကို error မပျက်အောင်ကိုင်တွယ်ပုံနဲ့ရှင်းပြထားပါတယ်။

🐍 Lesson 12: Python Error Handling (Try...Except)

1. Error Handling ဆိုတာဘာလဲ?

မြန်မာ → Python code run တဲ့အချိန်မှာ error (exception) တွေဖြစ်နိုင်တယ်။ Error handling ဆိုတာ အဲဒီ error တွေကို gracefully ကိုင်တွယ်ပြီး program မပျက်အောင် ဆက်လက်အလုပ်လုပ်နိုင်အောင် စီမံပေးတဲ့ နည်းလမ်း။

English → Error handling is the process of managing exceptions so that the program doesn't crash and can continue running smoothly.

2. Common Errors in Python

  • ZeroDivisionError → divide by zero
  • ValueError → invalid value
  • TypeError → wrong data type
  • FileNotFoundError → file not found

3. အကျဉ်းချုပ်

✅ Use try...except to handle errors gracefully

✅ Multiple except blocks handle different error types

else runs if no error occurs

finally always runs (cleanup, closing files)

python
# ===== 1. Basic Try...Except =====
try:
    x = 10 / 0
except ZeroDivisionError:
    print("You cannot divide by zero!")

# ===== 2. Multiple Except Blocks =====
print(f"\n===== Multiple Exceptions =====")

try:
    num = int("abc")
except ValueError:
    print("Invalid number")
except ZeroDivisionError:
    print("Division by zero")

# ===== 3. Catching Any Exception =====
print(f"\n===== Catch Any Exception =====")

try:
    x = 10 / 0
except Exception as e:
    print(f"Error occurred: {e}")

# ===== 4. Using else =====
print(f"\n===== Using else =====")

try:
    x = 5 / 1
except ZeroDivisionError:
    print("Error!")
else:
    print(f"Success: {x}")

# ===== 5. Using finally =====
print(f"\n===== Using finally =====")

try:
    f = open("data.txt")
    content = f.read()
except FileNotFoundError:
    print("File not found")
finally:
    print("Closing file (if opened)")

# ===== 6. Real-World Example =====
print(f"\n===== Safe Divide Function =====")

def safe_divide(a, b):
    try:
        return a / b
    except ZeroDivisionError:
        return "Cannot divide by zero"
    except TypeError:
        return "Invalid input type"
    finally:
        print("Division attempted")

print(safe_divide(10, 2))   # 5.0
print(safe_divide(10, 0))   # Cannot divide by zero
print(safe_divide(10, "a")) # Invalid input type
You should see
You cannot divide by zero! ===== Multiple Exceptions ===== Invalid number ===== Catch Any Exception ===== Error occurred: division by zero ===== Using else ===== Success: 5.0 ===== Using finally ===== File not found Closing file (if opened) ===== Safe Divide Function ===== Division attempted 5.0 Division attempted Cannot divide by zero Division attempted Invalid input type
Try...Except (Enhanced) | Thuta Learning