JavaScript · Lesson 12 of 15
Errors and Debugging
try/catch/finally, throwing errors, custom errors and debugging tools.
- Intermediate
- 13 min read
- 3 objectives
Before this lessonLesson 11: Modules: import and export
What you will learn
- Catch and throw errors
- Create custom errors
- Debug with the console and devtools
Your Progress
0 of 15 lessons 0%
- Lessons0 / 15
- Completed0
- Est. time left~ 3 hours
Create a free account to keep your progress on every device.
When something goes wrong JavaScript throws an error. If nothing catches it, the program stops. try/catch lets you respond instead.
try, catch, finally
function parse(json) {
try {
return JSON.parse(json);
} catch (err) {
console.log("bad json:", err.name);
return null;
} finally {
console.log("done");
}
}
console.log(parse('{"a":1}'));
console.log(parse("{oops"));Output
done
{ a: 1 }
bad json: SyntaxError
done
nullfinally always runs, which makes it the place for cleanup.
Throwing and custom errors
class ValidationError extends Error {
constructor(field, message) {
super(message);
this.name = "ValidationError";
this.field = field;
}
}
function setAge(age) {
if (age < 0) throw new ValidationError("age", "age cannot be negative");
return age;
}
try {
setAge(-1);
} catch (e) {
if (e instanceof ValidationError) console.log(e.field, "-", e.message);
else throw e; // do not swallow unknown errors
}Output
age - age cannot be negative
Async errors
async function load() {
try {
const res = await fetch("https://example.invalid/data");
return await res.json();
} catch (e) {
console.log("request failed");
}
}
load();
Promise.reject(new Error("x")).catch(e => console.log(e.message));Debugging tools
console.log,console.table(array),console.errorandconsole.time/timeEnd.- The
debugger;statement pauses execution when devtools are open. - Devtools Sources tab: set breakpoints, step through code, watch variables. Read the stack trace from the top: the first line of your own code is usually the culprit.
