Sebuah skrip pendek menjumlahkan menit di dalam berkas CSV dan mencetak satu baris berisi total. Lalu satu sel kosong. Skripnya mati dengan traceback dan tidak mencetak apa pun, jadi baris yang sudah terbaca benar ikut lenyap bersamanya. Kamu kehilangan seluruh laporan gara-gara satu kolom kosong.
Poin Penting
- Satu sel kosong melempar
ValueErrordan menghentikan jalan sebelum totalnya tercetak, jadi baris yang sudah terbaca benar ikut hilang. trydi sekitar satu konversi itu danexcept ValueErrormelewati baris tersebut, menghitungnya, dan membiarkan loop sampai ke ujung.finallyberjalan entah bloknya berhasil atau melempar, itulah sebabnya baris ringkasan tercetak sebelum error berkas yang hilang.except:tanpa nama juga menelansys.exit()dan Ctrl-C, jadi sebutkan exception yang kamu harapkan.
Ketika skripnya mati
Simpan ini sebagai sessions.csv. Baris untuk 2026-11-04 punya kolom minutes yang kosong.
date,minutes
2026-11-03,20
2026-11-04,
2026-11-05,30
Simpan skrip awalnya sebagai totals.py. Skrip ini mengambil path berkas dari baris perintah dan menjumlahkan kolom minutes. csv.DictReader memberimu satu dict per baris dengan nilai berupa string, jadi skripnya mengonversi tiap nilai dengan int.
# totals.py
import csv
import sys
path = sys.argv[1]
total = 0
with open(path, newline="") as handle:
for row in csv.DictReader(handle):
total += int(row["minutes"])
print(f"total {total}")
Menjalankannya pada berkas itu berakhir dengan traceback dan status keluar 1.
$ python3 totals.py sessions.csv 2>&1 | tail -2
total += int(row["minutes"])
ValueError: invalid literal for int() with base 10: ''
Baris terakhir menyebut masalahnya. int("") tidak punya apa pun untuk dikonversi, jadi ia melempar ValueError. Tidak ada yang tercetak sebelum traceback, jadi dua baris yang sehat juga tidak mencetak apa pun.
Checker check_totals.py mengubah kegagalan ini menjadi angka. Ia menulis sessions.csv sendiri, menjalankan totals.py di proses anak, dan menghitung pemeriksaan yang lolos.
# check_totals.py
import subprocess
import sys
from pathlib import Path
ROWS = """date,minutes
2026-11-03,20
2026-11-04,
2026-11-05,30
"""
def run(path):
return subprocess.run([sys.executable, "totals.py", path], text=True, capture_output=True)
def report(results):
for label, passed, detail in results:
mark = "PASS" if passed else "FAIL"
note = f" <- {detail}" if detail and not passed else ""
print(f"{mark} {label}{note}")
passed = [ok for _, ok, _ in results].count(True)
print(f"\n{passed} of {len(results)} checks passed")
def main():
path = Path("sessions.csv")
path.write_text(ROWS)
run_ok = run(str(path))
crashed = run_ok.returncode != 0
last = run_ok.stderr.strip().splitlines()[-1] if run_ok.stderr.strip() else ""
results = [("the script finishes on a file with one blank field", not crashed, last)]
if crashed:
report(results)
return 1
out = run_ok.stdout
lines = [line for line in out.splitlines() if line.strip()]
results.append(("it prints the total of the rows it could read", "total 50" in out, out.strip()))
results.append(("it says which row it skipped", "2026-11-04" in out, out.strip()))
results.append(("it prints one line per skipped row", len(lines) == 2, str(lines)))
run_missing = run("no_such_file.csv")
results.append(("it still reports the summary when the file is missing", "read 0 rows" in run_missing.stdout, run_missing.stdout.strip()))
results.append(("the missing file still raises", run_missing.returncode != 0, f"exit {run_missing.returncode}"))
report(results)
return 0 if all(ok for _, ok, _ in results) else 1
if __name__ == "__main__":
sys.exit(main())
Terhadap versi awal, checker mencetak nol dan keluar dengan status 1.
$ python3 check_totals.py
FAIL the script finishes on a file with one blank field <- ValueError: invalid literal for int() with base 10: ''
0 of 1 checks passed
Perbaikan seminimal mungkin
Bungkus hanya konversinya dengan try. Saat int melempar, Python melompat ke except yang cocok dan melewati sisa blok try. Baris yang dilewati menambah satu ke penghitung dan mencetak tanggalnya, lalu loop lanjut ke baris berikutnya.
!r di f-string mencetak repr dari nilainya, jadi string kosong muncul sebagai '' alih-alih menghilang. finally di bagian bawah mencetak baris ringkasan.
# totals.py
import csv
import sys
path = sys.argv[1]
total = 0
read = 0
skipped = 0
try:
with open(path, newline="") as handle:
for row in csv.DictReader(handle):
read += 1
try:
total += int(row["minutes"])
except ValueError:
skipped += 1
print(f"skipped {row['date']}: {row['minutes']!r}")
finally:
print(f"read {read} rows, skipped {skipped}, total {total}")
Jalannya sekarang selesai dengan status keluar 0. Ketiga baris terhitung terbaca, yang kosong dilewati, dan totalnya 50.
$ python3 totals.py sessions.csv
skipped 2026-11-04: ''
read 3 rows, skipped 1, total 50
Error lain tetap sampai ke kamu, karena except ValueError hanya menangkap ValueError dan turunannya.
Kenapa finally
Arahkan skrip yang sudah diperbaiki ke berkas yang tidak ada.
$ python3 totals.py no_such_file.csv 2>&1 | sed -n '1p;$p'
read 0 rows, skipped 0, total 0
FileNotFoundError: [Errno 2] No such file or directory: 'no_such_file.csv'
Baris ringkasannya tercetak, dan errornya masih ada di akhir. Blok finally berjalan entah bloknya berhasil, melempar, atau return. Berbeda dari except, ia tidak menangkap exception; ia menjalankan pembersihannya lalu membiarkan errornya merambat.
Checker mencakup kedua jalannya, kolom kosong dan berkas yang hilang, dan keenam pemeriksaan lolos dengan status keluar 0.
$ python3 check_totals.py
PASS the script finishes on a file with one blank field
PASS it prints the total of the rows it could read
PASS it says which row it skipped
PASS it prints one line per skipped row
PASS it still reports the summary when the file is missing
PASS the missing file still raises
6 of 6 checks passed
Jebakannya
except: tanpa nama sama dengan except BaseException:, jadi ia menangkap lebih dari sekadar error. Berkas yang memanggil sys.exit(3) di dalam try dengan except: tanpa nama mencetak swallowed dan keluar dengan status 0. Berkas yang melempar KeyboardInterrupt di dalam try dengan except: tanpa nama mencetak bare except swallowed it dan keluar dengan status 0. Keluar yang disengaja dan Ctrl-C sama-sama berubah jadi jalan yang sukses.
Sekarang rusak salinanmu sendiri. Hapus baris finally: dari totals.py dan kurangi indentasi print ringkasannya. Checker melaporkan 5 of 6 checks passed dan keluar dengan status 1, karena jalan untuk berkas yang hilang jadi tidak mencetak ringkasan sama sekali.