0
0
Node.jsframework~10 mins

Try-catch for synchronous errors in Node.js - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Try-catch for synchronous errors
Start
Try block runs
Error thrown?
NoTry block ends normally
Yes
Catch block runs
Continue after catch
End
The code inside try runs first. If an error happens, catch runs to handle it. Then code continues after catch.
Execution Sample
Node.js
try {
  const result = 10 / 0;
  console.log('Result:', result);
} catch (error) {
  console.log('Error caught:', error.message);
}
This code tries to divide 10 by 0 and logs the result. If an error happens, it catches and logs the error message.
Execution Table
StepActionEvaluationResult
1Enter try blockNo error yetProceed
2Calculate 10 / 010 / 0 = Infinity (no error in JS)Infinity
3console.log('Result:', Infinity)Prints to consoleOutput: Result: Infinity
4Try block endsNo error thrownCatch block skipped
5Continue after try-catchProgram continues normallyEnd
💡 No error thrown, so catch block is skipped and program ends normally
Variable Tracker
VariableStartAfter Step 2Final
resultundefinedInfinityInfinity
Key Moments - 2 Insights
Why doesn't dividing by zero throw an error in JavaScript here?
Because in JavaScript dividing by zero returns Infinity, not an error. See execution_table step 2 where 10 / 0 evaluates to Infinity without throwing.
When does the catch block run?
The catch block runs only if an error is thrown inside the try block. In this example, no error is thrown, so catch is skipped (execution_table step 4).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'result' after step 2?
A0
BError
CInfinity
Dundefined
💡 Hint
Check the 'Evaluation' and 'Result' columns in row for step 2.
At which step does the catch block run in this example?
ACatch block does not run
BStep 4
CStep 3
DStep 2
💡 Hint
Look at the 'Result' column for step 4 about catch block execution.
If the code inside try threw an error, what would happen next?
ATry block continues normally
BCatch block runs to handle the error
CProgram crashes immediately
DError is ignored
💡 Hint
Refer to the concept_flow where error leads to catch block execution.
Concept Snapshot
try {
  // code that might throw error
} catch (error) {
  // handle error here
}

- Runs try block first
- If error thrown, catch runs
- If no error, catch skipped
- Only synchronous errors caught
Full Transcript
This example shows how try-catch works in Node.js for synchronous code. The try block runs first. If an error happens inside try, the catch block runs to handle it. If no error happens, catch is skipped and code continues normally. In the example, dividing 10 by 0 does not throw an error in JavaScript; it returns Infinity. So catch block does not run. This helps prevent crashes by catching errors and handling them gracefully.