This is the answer article. If you have not worked lab 0005 and still want to try it yourself, close this page first. Everything below is the answer, with the measured numbers.
Key takeaways
- One bad line must not stop the whole run. Report it, then move to the next line.
- The file line number comes from
enumerate(pembaca, start=2)— line 1 is the header, not data. IndexErrormeans you have not validated yet. Check the column count before touching the row's contents.- The exit code is a contract:
0done,1rows are broken,2you are using it wrong.
The full numbers
Two states, measured with the same scripts/check.py, on the same machine, without changing data/
or scripts/check.py at all:
| variant | green | note |
|---|---|---|
initial state (main branch) |
1 of 7 | only A: periksa() throws int(baris[2]), and whoever calls it stops there |
all problems collected, line numbers start=2, exit codes 0/1/2 |
7 of 7 | — |
The concrete numbers, if you want to match them against your own laptop. At the initial state,
beberapa.csv blows up with ValueError: invalid literal for int() with base 10: 'dua puluh' and
only 0 of 4 problems reported. kosong.csv produces no complaint at all, then still claims
3 baris diimpor with exit code 0, while holding a row with no name. kolom.csv explodes with
IndexError: list index out of range, 0 of 2 problems. And tidak-ada.csv gives
FileNotFoundError with exit code 1, not 2.
On the solusi branch, make demo produces one report line per problem — four lines for
beberapa.csv, two for kolom.csv — with exit codes 0/1/2 matching the situation.
Why it is like this
periksa() prints instead of returning — and throws halfway through
umur = int(baris[2]) # ValueError if the contents are not a number
if umur < 1 or umur > 120:
print("umur tidak masuk akal, dilewati")
Two flaws in those two lines. First, int() throws and main() does not catch it: one bad line
stops the whole run, so the problems after it never get reported. Second, the only diagnostic is a
print that names neither the line nor the column.
What makes this trap slick is that the comment above it justifies both — "Python already gives a clear message", "only age can break the system". The code looks careful. What you actually need is the opposite rule: one bad line must not stop the whole run. Report it, then let the loop move on to the next line.
The line number is the caller's job, not the validator's
periksa() should return a list of problems and know nothing about line numbers. The piece that
attaches the number is main(), through enumerate(pembaca, start=2). That 2 is not a trivial
detail: line 1 of the file is the header, so the first data row is on line 2.
Start from start=1 and every number you report is off by exactly one from what the user sees in
their editor. This is the easiest off-by-one to miss in your own work, because the screen "looks
right". Only one thing separates them: the line number in the file belongs to the caller, while
the data index belongs to the validator.
IndexError means you have not validated yet
kolom.csv has rows with 2 columns and rows with 4, when the header has 3. Touching baris[2]
before confirming the column count is sufficient only relocates the crash. IndexError here means
you have not validated — it is not a sign of complicated data.
The right order: check the column count first. If len(baris) does not equal the expected number of
columns, report it as one problem in the jumlah kolom column, then do not continue into that row's
contents. Column by column cannot be trusted before the count matches.
The exit code is part of the contract
Scripts like this get called from make, cron, or a shell pipe. The caller does not read the
screen; it reads the exit code. "The file does not exist" and "the file exists but something in it
is wrong" are two different things to a caller — the first means you used it wrong, the second means
the data needs fixing.
Which is why the exit codes are separated: 0 done, 1 some rows are broken, 2 used wrongly
(file missing, argument missing). The initial state has one code for almost every failure, so a
caller automatically cannot decide whether to retry, stop, or continue.
The shape of the fix
Validation becomes a function that collects instead of throwing:
def periksa(baris):
masalah = []
if len(baris) != len(KOLOM):
masalah.append(("jumlah kolom", "... seharusnya ..."))
return masalah
nama, email, umur = (sel.strip() for sel in baris)
if not nama:
masalah.append(("nama", "kolom nama kosong, padahal harus diisi"))
if "@" not in email:
masalah.append(("email", f"'{email}' bukan alamat email karena tidak ada tanda '@'"))
try:
umur_angka = int(umur)
except ValueError:
masalah.append(("umur", f"'{umur}' bukan angka — isi dengan bilangan bulat, misalnya 25"))
return masalah
then in main() the line number gets attached from the file row:
for nomor, baris in enumerate(pembaca, start=2): # baris 1 file = judul
for kolom, pesan in periksa(baris):
sys.stderr.write(f"baris {nomor}: {kolom} — {pesan}\n")
A correct line returns an empty list, so nothing is reported. A broken line can return more than
one problem at once — in beberapa.csv there is a row with an empty name and an email with no
@. Note also that the try/except is small and specific, wrapping only int(umur). Do not wrap
everything in one big try/except in main(): that does remove the stack trace, but it also stops
the program at the first bad line, and you are back where you started.
What to take from this
A useful error message answers three things — where, what is wrong, and what it should be — and it answers all of them at once, not just the first one it happened to hit. A program that stops at the first problem answers a third of that. The time you save there gets paid for on the phone call.
One habit changes: before you write raise, ask who is going to read the message.