Error Handling: Try/Except
Python menggunakan try/except untuk menangani error (exception) yang terjadi saat runtime.
Sintaks Dasar
try:
result = 10 / 0
except ZeroDivisionError:
print("Tidak bisa dibagi nol!")
try:
angka = int("abc")
except ValueError:
print("Bukan angka yang valid!")
Multiple Exceptions
try:
data = {"nama": "Budi"}
print(data["umur"])
except KeyError as e:
print(f"Key tidak ditemukan: {e}")
except TypeError:
print("Tipe data salah")
Try/Except/Finally
try:
file = open("data.txt")
content = file.read()
except FileNotFoundError:
print("File tidak ditemukan")
finally:
print("Blok ini selalu dijalankan")
Raise Exception
def bagi(a, b):
if b == 0:
raise ValueError("Pembagi tidak boleh nol")
return a / b