Python
121 ~25 dk
Hata Yakalama (try-except)
Hata Türleri
| Hata | Sebep | Örnek |
|---|---|---|
ValueError | Yanlış değer | int("abc") |
TypeError | Yanlış tip | "2" + 3 |
ZeroDivisionError | Sıfıra bölme | 10 / 0 |
IndexError | Geçersiz indeks | liste[99] |
FileNotFoundError | Dosya yok | open("yok.txt") |
try-except Yapısı
try:
sayi = int(input("Sayı girin: "))
sonuc = 100 / sayi
print(f"Sonuç: {sonuc}")
except ValueError:
print("❌ Geçerli bir sayı girin!")
except ZeroDivisionError:
print("❌ Sıfıra bölme hatası!")
except Exception as e:
print(f"❌ Hata: {e}")
else:
print("✅ Başarılı!")
finally:
print("Program bitti.")
>>> python hata.py
Sayı girin: abc
❌ Geçerli bir sayı girin!
Program bitti.Güvenli Input Fonksiyonu
def sayi_al(mesaj):
while True:
try:
return float(input(mesaj))
except ValueError:
print("⚠️ Geçerli bir sayı girin!")
not1 = sayi_al("1. notu girin: ")
not2 = sayi_al("2. notu girin: ")
print(f"Ortalama: {(not1 + not2) / 2:.1f}")
raise ile Hata Fırlatma
def yas_kontrol(yas):
if yas < 0:
raise ValueError("Yaş negatif olamaz!")
return f"Yaşınız: {yas}"
try:
print(yas_kontrol(-5))
except ValueError as e:
print(f"Hata: {e}")
🎯 Alıştırmalar
- Güvenli hesap makinesi (tüm hataları yakalayan)
- Dosya okurken hata yakalama
- 1-100 arası not alan, geçersiz girişte tekrar soran program
- Özel hata sınıfı oluşturup kullanan program