Concept Flow - Throwing errors
Start
Check condition
Yes
Throw error
Catch error?
No→Program stops
Yes
Handle error
Continue or Exit
The program checks a condition, throws an error if needed, then either catches and handles it or stops.
function checkAge(age) { if (age < 18) { throw new Error('Too young'); } return 'Allowed'; } checkAge(15);
| Step | Action | Condition | Result | Output/Error |
|---|---|---|---|---|
| 1 | Call checkAge(15) | age = 15 | Check if 15 < 18 | No output yet |
| 2 | Condition true | 15 < 18 | Throw new Error('Too young') | Error thrown: Too young |
| 3 | No catch block | Error not caught | Program stops | Uncaught Error: Too young |
| Variable | Start | After Step 1 | After Step 2 | Final |
|---|---|---|---|---|
| age | undefined | 15 | 15 | 15 |
Throw errors with throw new Error('message')
Use if conditions to decide when to throw
If error not caught, program stops
Use try-catch to handle errors
Throwing interrupts normal flow
Errors carry messages for debuggingthrow statement do in JavaScript?throwthrow statement is used to create an error and stop normal program execution.try...catch which handles errors, throw actually creates the error.throw creates error = A [OK]new Error('message').throw new Error('Invalid input'); which is correct syntax.new Error = C [OK]try {
throw new Error('Oops!');
} catch (e) {
console.log(e.message);
}e.message.e.message containse.message is the string 'Oops!'. So console.log(e.message) prints 'Oops!'.try {
throw new Error('Fail');
} catch e {
console.log(e.message);
}catch (e).catch e without parentheses, which causes a syntax error.!input is true if input is null, undefined, empty string, 0, or false.if (!input) throw new Error('Input required'); which covers empty string and null correctly with proper syntax.Pass the test and this pattern moves unknown