Exceptions · Pengecualian
When things go wrong
- A runtime error normally crashes the program.
- An exception is Python's signal that something went wrong.
- Exception handling lets you catch it and keep running.
Ketika terjadi kesalahan
- Error runtime biasanya menghentikan program.
- Exception adalah sinyal Python bahwa ada sesuatu yang salah.
- Penanganan exception memungkinkan Anda menangkapnya dan tetap berjalan.
try / except
- Put risky code in a
try:block. - If it raises an exception, the
except:block runs instead of crashing. - If nothing goes wrong, the
exceptblock is skipped.
try / except
- Masukkan kode berisiko ke dalam blok
try:. - Jika itu memunculkan exception, blok
except:berjalan alih-alih crash. - Jika tidak ada yang salah, blok
exceptdilewati.
try:
number = int("not a number")
except ValueError:
number = 0
print(number)
Catch the right error
- Name the type of error you expect:
except ValueError:. ValueErroris bad text for a number;ZeroDivisionErroris divide by zero.- Catching a specific type means you do not hide other bugs.
Tangkap error yang tepat
- Sebutkan jenis error yang Anda harapkan:
except ValueError:. ValueErroradalah teks buruk untuk angka;ZeroDivisionErroradalah bagi dengan nol.- Menangkap jenis spesifik berarti Anda tidak menyembunyikan bug lain.
try:
print(10 / 0)
except ZeroDivisionError:
print("Cannot divide by zero")
finally and raise
- A
finally:block always runs, error or not — good for cleanup. raiselets you signal an error on purpose.raise ValueError("message")stops the code unless something catches it.
finally dan raise
- Blok
finally:selalu berjalan, dengan atau tanpa error — bagus untuk pembersihan. raisememungkinkan Anda memberi sinyal error dengan sengaja.raise ValueError("message")menghentikan kode kecuali ada yang menangkapnya.
try:
raise ValueError("bad value")
except ValueError as e:
print("Caught:", e)
finally:
print("Always runs")
Why it matters
- A robust program should not crash on bad input.
- Handling exceptions lets it warn the user and carry on.
- It also makes sure files and other resources are closed cleanly.
Mengapa ini penting
- Program yang tangguh tidak seharusnya crash pada input buruk.
- Menangani exception memungkinkannya memberi peringatan pada pengguna dan melanjutkan.
- Ini juga memastikan file dan sumber daya lainnya ditutup dengan bersih.
Common mistakes
- Catch a specific error (
except ValueError:), not a bareexcept:. - Put only the risky line inside the
try.
Kesalahan umum
- Tangkap error spesifik (
except ValueError:), bukanexcept:telanjang. - Masukkan hanya baris berisiko di dalam
try.
Now you try
- Use
try/except(andraisein the last task). - Press Check answer to test your code.
Sekarang Anda coba
- Gunakan
try/except(danraisedi tugas terakhir). - Tekan Periksa jawaban untuk menguji kode Anda.
try / except
Code runs in try; if it fails, control jumps to except. · Kode berjalan di try; jika gagal, alih-alih kontrol berpindah ke except.
Write safe_int(text) that returns int(text). If the text is not a valid number, catch the ValueError and return -1 instead. · Tulis safe_int(text) yang mengembalikan int(text). Jika teks bukan angka yang valid, tangkap ValueError dan kembalikan -1 sebagai gantinya.
Click Run to see the output here. · Klik Jalankan untuk melihat output di sini.
Write divide(a, b) that returns a / b. If b is 0, catch the ZeroDivisionError and return None instead. · Tulis divide(a, b) yang mengembalikan a / b. Jika b adalah 0, tangkap ZeroDivisionError dan kembalikan None sebagai gantinya.
Click Run to see the output here. · Klik Jalankan untuk melihat output di sini.
Write withdraw(balance, amount). If amount is more than balance, raise ValueError. Otherwise return the new balance (balance - amount). · Tulis withdraw(balance, amount). Jika amount lebih besar dari balance, raise ValueError. Sebaliknya kembalikan saldo baru (balance - amount).
Click Run to see the output here. · Klik Jalankan untuk melihat output di sini.