Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now!
This site is generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join 11 million other learners and get started learning Python for data science today!
Good news! You can save 25% off your Datacamp annual subscription with the code LEARNPYTHON23ALE25 - Click here to redeem your discount
Penanganan Pengecualian
When programming, errors happen. It's just a fact of life. Mungkin pengguna memberikan input yang buruk. Mungkin sumber daya jaringan tidak tersedia. Mungkin program kehabisan memori. Atau mungkin programmer bahkan melakukan kesalahan!
Solusi Python terhadap kesalahan adalah pengecualian. Anda mungkin sudah pernah melihat pengecualian sebelumnya.
print(a)
#error
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
Ups! Lupa untuk menetapkan nilai ke variabel 'a'.
Tetapi terkadang Anda tidak ingin pengecualian sepenuhnya menghentikan program. Anda mungkin ingin melakukan sesuatu yang spesial ketika pengecualian terjadi. Ini dilakukan dalam blok try/except.
Ini adalah contoh sederhana: Misalkan Anda sedang mengiterasi atas sebuah daftar. Anda perlu mengiterasi atas 20 angka, tetapi daftar ini dibuat dari input pengguna dan mungkin tidak memiliki 20 angka di dalamnya. Setelah Anda mencapai akhir daftar, Anda hanya ingin sisa angka diinterpretasikan sebagai 0. Berikut adalah cara untuk melakukannya:
def do_stuff_with_number(n):
print(n)
def catch_this():
the_list = (1, 2, 3, 4, 5)
for i in range(20):
try:
do_stuff_with_number(the_list[i])
except IndexError: # Raised when accessing a non-existing index of a list
do_stuff_with_number(0)
catch_this()
Nah, itu tidak terlalu sulit! Anda bisa melakukan itu dengan pengecualian apapun. Untuk detail lebih lanjut tentang menangani pengecualian, lihat saja Python Docs
Exercise
Tangani semua pengecualian! Ingat kembali pelajaran sebelumnya untuk mengembalikan nama belakang aktor.
# Setup
actor = {"name": "John Cleese", "rank": "awesome"}
# Function to modify!!!
def get_last_name():
return actor["last_name"]
# Test code
get_last_name()
print("All exceptions caught! Good job!")
print("The actor's last name is %s" % get_last_name())
actor = {"name": "John Cleese", "rank": "awesome"}
def get_last_name():
return actor["name"].split()[1]
get_last_name()
print("All exceptions caught! Good job!")
print("The actor's last name is %s" % get_last_name())
test_output_contains("Cleese")
test_output_contains("All exceptions caught! Good job!")
test_output_contains("The actor's last name is Cleese")
success_msg("Great work!")
This site is generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today!