JavaScript throw: Report Meaningful Failures
Quick answer
Throw interrupts normal evaluation with an exception. Error objects provide a recognizable type and message that callers can inspect.
How it works
throw new Error(message) throws an object; JavaScript permits any thrown value but Error objects are a useful convention. Execution leaves the current path until a matching catch is found. A line terminator is not permitted between throw and its expression. The examples use try/catch as a preview of the next lesson.
function readCount(n) { if (n < 0) throw new Error("Negative count"); return n; }try { readCount(-1); } catch (error) { console.log(error.message); }Expected output in Node.js:
Negative countThrow transfers control to the catch, which reads the message.
try { throw new Error("Missing item"); console.log("later"); } catch (error) { console.log(error.name); }Expected output in Node.js:
ErrorThe log after throw is unreachable in that execution path.
Common mistakes
Throwing a string loses the conventional Error structure; avoid including private input or secrets in messages.
Practice
Trace which messages execute before and after a thrown Error; avoid secret data in the message.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript throw: Report Meaningful Failures — Knowledge Check
Apply the taught concept and predict the output.
What happens to statements after a throw on the same normal path?
Which is a useful conventional value to throw?
Which syntax is invalid between throw and its expression?
What is the exact console output in JavaScript throw: Report Meaningful Failures example 1?
function readCount(n) { if (n < 0) throw new Error("Negative count"); return n; }try { readCount(-1); } catch (error) { console.log(error.message); }What is the exact console output in JavaScript throw: Report Meaningful Failures example 2?
try { throw new Error("Missing item"); console.log("later"); } catch (error) { console.log(error.name); }