In this video, you caught the SyntaxError from Ruth’s hand-edited season file and watched which lines of main.js run, and in what order, when a line inside try throws.
Key Points
- Ruth typed a seventh run into
runs.jsonby hand and left a comma after its last value.JSON.parse()throws aSyntaxErrorinsideloadRuns(), and because nothing catches it, the whole program stops with a report and no runs print. - A
trystatement wraps the lines that might throw. If any line in thetryblock throws, thecatchblock runs instead, and itserrorparameter holds the error that was thrown. - The error is an object. Its
.nameproperty names the error’s type, and its.messageproperty is the text after it. Together, they make up the error line in a report. - When line 5 throws, the rest of
tryis skipped and JavaScript jumps straight tocatch, soprintSeason()never runs. Aftercatchfinishes, the program carries on after the whole statement and ends normally. - Watch out: once
catchhas run, JavaScript never goes back intotry. Anything that should still happen goes after the statement. - A
finallyblock always runs on the way out of the statement, whethertryfinished orcatchran. - Inside a function, a
returnintryorcatchleaves before the line after the statement, but it can’t skipfinally. The toysketch.jsbelow has nocatchat all, since atrycan be followed byfinallyalone. Itstryreturns, yet the line infinallyprints first, and only then does the function hand back its text. The line after the statement inside the function never runs. - So a throw in
tryjumps tocatch, thenfinally, which always runs. Oncecatchandfinallyfinish without areturn, the line after the statement runs. It never goes back intotry. - With the comma removed,
tryfinishes,catchis skipped, andfinallyand the line after the statement run as before.
Final Code
Ruth’s other files in the season-log folder haven’t changed in this video, apart from Grace Kim’s run at the end of runs.json: