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 debugging