← Kembali ke kursus
Pelajaran kursus · Python
Pelajaran 32

Exception handling: try/except/else/finally

Tangkap error tanpa program mati, dengan raise dan finally.

Pahami konsepnya

Python menangani error lewat exception: int("abc") melempar ValueError yang menghentikan program. try/except menangkapnya: bungkus kode berisiko di try, tangani di except — program tetap hidup. Bentuk lengkapnya empat blok: try (kode berisiko), except (saat error), else (saat sukses), finally (selalu, cocok untuk cleanup).

Tipe exception yang umum: ValueError (konversi gagal), TypeError (operasi tipe salah), ZeroDivisionError, IndexError (indeks di luar), KeyError (kunci dict tidak ada), FileNotFoundError. Tangkap tipe spesifik alih-alih Exception yang telanjang — menelan semua error menyembunyikan bug.

raise melempar exception sendiri: raise ValueError("harga tidak boleh negatif"). Ini cara fungsi memberi tahu pemanggil bahwa masalah terjadi — pemanggil yang menangkap atau meneruskannya.

Coba contoh kode

def bagi(a, b):
    if b == 0:
        raise ZeroDivisionError("pembagi tidak boleh nol")
    return a / b

try:
    hasil = bagi(10, 2)
except ZeroDivisionError as e:
    print(f"Gagal: {e}")
else:
    print(f"Hasil: {hasil}")
finally:
    print("Selesai.")

# input aman dengan loop
while True:
    try:
        umur = int(input("Umur: "))
        if 1 <= umur <= 120:
            break
        print("Di luar rentang wajar.")
    except ValueError:
        print("Angka saja ya.")

Fungsi bagi melempar raise saat pembagi nol; try menangkapnya tanpa mematikan program. else berjalan saat try sukses; finally selalu — cocok untuk menutup berkas atau koneksi. Loop baca-ulang dengan try/except memvalidasi input hingga sah.

Latihan singkat

Uji: input `abc` lalu `60` — harus berakhir `60`.