Errors and try/catch
Handling problems.
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.

- 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.
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.");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.
| key | value |
|---|---|
| SyntaxError | badly written code or JSON |
| ReferenceError | unknown variable |
| TypeError | wrong kind of value |
| finally | always 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