Plan for things going wrong

INPUT · Slides

Not stopping at an error

01 / 05

An error comes out and it stops there

So far an error has been "something to fix when it comes out". But things can fail for reasons other than mistyping — data arriving from outside is a different shape from what you thought, an entry that should be there is not, and so on.

When an error happens, the program stops on that line. The lines written after it no longer run. In the example below, end never comes out.

const fruits = ["apple"];console.log("start");fruits.add("peach");console.log("end");

Result

start
TypeError: fruits.add is not a function

02 / 05

Catch it with try and catch

Write the work that might fail inside try { }, and what to do when it failed in catch { }.

When an error happens it does not stop there but jumps into the catch. Once out of the catch, the rest runs as though nothing happened.

const fruits = ["apple"];try {  fruits.add("peach");} catch (error) {  console.log("could not add");}console.log("the rest still runs");

Result

could not add
the rest still runs

03 / 05

Read what is inside the error

The name you wrote in the catch's brackets (error here) catches the error that happened itself.

Look at message and you can read in words what happened. It is the part after the TypeError: you were seeing on screen. When you want to chase a cause, showing this gives you a clue.

const box = {};try {  box.open();} catch (error) {  console.log(error.message);}

Result

box.open is not a function

04 / 05

finally always runs last

Add finally { } after the catch and its inside always runs last, whether things succeeded or failed.

It is the place for work you want done either way, like "call it finished" or "tidy up".

try {  console.log("loading");  const memo = {};  memo.save();} catch (error) {  console.log("that failed");} finally {  console.log("tidied up");}

Result

loading
that failed
tidied up

05 / 05

Only wrap what you can decide about

Wrap it in a try and the error stops coming out. But what disappeared is the error, not the problem. Do nothing inside the catch and nobody can notice the failure, and it carries on running.

Wrap only where "you know it can fail and you can decide what to do when it does". When in doubt, try thinking first about what you would write in the catch.

Right — let us practise catching.