In the last lesson, Ruth wrote a catch that handles the one error it expects, a SyntaxError from JSON.parse(), and lets every other error through. With her hand-typed file fixed, she types in the next Saturday’s runs and wants the season’s total minutes. One of the times arrived as a word, and she reaches for the tool from the last lesson.
In this lesson, you’ll see why a try can’t protect your program from bad input when the operation doesn’t throw and how to check the value with an if instead. You’ll also get a short list of what throws and what quietly gives back a special value. Start with the code Ruth writes to add up the minutes.
Wrap the Conversion in a try
Ruth’s season-log project is as the last lesson left it, with the small try in loadRuns(). If you don’t have the files anymore, re-create them in a season-log folder:
This package.json tells Node.js to treat the .js files as ES modules:
package.json
{ "type": "module" }
The loader in load.js parses a file’s text and reports a broken file by name:
load.js
import { readFileSync } from "node:fs";
export function loadRuns(path) {
const text = readFileSync(path, "utf-8");
let runs = [];
try {
runs = JSON.parse(text);
} catch (error) {
if (error instanceof SyntaxError) {
console.log(`Couldn't read ${path}.`);
console.log(`${error.name}: ${error.message}`);
} else {
throw error;
}
}
return runs;
}
The report in report.js formats and prints each run:
report.js
export function formatRun(run) {
const who = `${run.runner} (${run.date})`;
return `${who}: ${run.distance} km in ${run.minutes} min`;
}
export function printSeason(runs) {
for (let i = 0; i < runs.length; i++) {
console.log(formatRun(runs[i]));
}
}
Ruth’s hand-typed new-runs.json now holds the runs from May 2, copied from the runners’ messages:
new-runs.json
[
{ "id": 9, "runner": "Tomás Herrera", "date": "2026-05-02",
"distance": 10, "minutes": 56 },
{ "id": 10, "runner": "Kwame Mensah", "date": "2026-05-02",
"distance": 8, "minutes": "38" },
{ "id": 11, "runner": "Ruth Abebe", "date": "2026-05-02",
"distance": 5, "minutes": "forty" }
]
Two of the minutes values are strings. Kwame’s "38" is text with a number in it, and the time on Ruth’s own run is the word "forty". Adding a string to a number with + joins them as text, so Ruth converts each value with Number() before she adds it.
Ruth knows "forty" can’t become a number, so she expects Number() to fail on it. She puts the conversion in a try, as the last lesson taught: catch only the error you expect, which she guesses is a TypeError, and rethrow the rest. Her new totals.js adds up the minutes:
totals.js
export function seasonMinutes(runs) {
let total = 0;
for (const run of runs) {
try {
total += Number(run.minutes);
} catch (error) {
if (error instanceof TypeError) {
console.log(`Run ${run.id}: bad minutes`);
} else {
throw error;
}
}
}
return total;
}