Catching Errors

Sometimes an error is expected and you want to handle it rather than crash. A file might be missing, a user might type letters into a number field, a network might be down.

Both languages wrap risky code in a try block and handle problems in a second block.

Try and catch

PYTHON

try:
    value = int(text)
except ValueError:
    value = 0
    print("Not a number, using 0")

JAVASCRIPT

let value;
try {
  value = Number(text);
  if (Number.isNaN(value)) throw new Error("bad");
} catch (err) {
  value = 0;
  console.log("Not a number, using 0");
}
Compare → Python names the specific error it expects to catch, which is good practice. JavaScript catches everything in one block, so you often have to throw deliberately when a value is wrong but did not raise on its own.
EXAMPLE
loading editor…
YOUR TURN
Your turn → Add "3.5" and an empty string to the entries, then run it and see which ones are skipped.
loading editor…

Syntax has to be exact. Every quote, bracket and parenthesis needs its partner, and in Python the spaces at the start of a line count. One slip and the program won't run; the message will say where.

✦ Catch narrowly

Catching every possible error and ignoring it hides real bugs. Catch the specific error you expect and let anything unexpected surface. A silent program that produces wrong answers is far worse than one that stops and tells you.

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Raising Your Own, and finally →
← Back