AI Hints
Home›JavaScript Tutorial›Getters and Errors
JavaScript · Lesson 74 of 138

Errors and try/catch

Handling problems.

⏱ 2 min read▶ Video at 1:29:54🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

Things go wrong. A file is missing, the network is down, or the data is broken. Without handling, an error stops your whole program. Try and catch let you handle the problem, and carry on.

Errors and try/catch
From the video: Errors and try/catch
  • Things go wrong
  • Errors stop programs
  • try and catch

Catching an error

Code that might fail goes in the try block. If anything throws an error, JavaScript jumps straight to catch, and gives us the error object. Its name and message describe what went wrong. Finally always runs, error or not. And the program keeps going afterwards. Run it.

app.jsjavascript
const text = '{"name": "Ana", }';

try {
  const data = JSON.parse(text);
  console.log("Parsed:", data);
} catch (error) {
  console.log("Could not parse:", error.name);
} finally {
  console.log("Finished trying.");
}

console.log("The program keeps going.");
Output
Could not parse: SyntaxError
Finished trying.
The program keeps going.

Common error types

A syntax error means the code, or JSON, isn't written correctly. A reference error means you used a variable that doesn't exist. A type error means you used a value the wrong way, like calling something that isn't a function, or reading a property of undefined. Reading the error's name is the first step in debugging.

keyvalue
SyntaxErrorbadly written code or JSON
ReferenceErrorunknown variable
TypeErrorwrong kind of value
finallyalways runs

Summary

Try runs risky code, catch handles any error, and finally always runs. Next, throwing errors of your own.

Key takeaways
  • try { } catch (e) { }
  • e.name and e.message
  • finally
Next up: Throwing Errors — your own errors