Recall & Review
beginner
What is the purpose of a try-catch block in Node.js?
A try-catch block is used to handle errors that happen during the execution of synchronous code. It lets the program continue running instead of crashing.
Click to reveal answer
beginner
Which type of errors can be caught by a try-catch block?
Try-catch blocks catch synchronous errors only. They do not catch errors from asynchronous code like promises or callbacks.
Click to reveal answer
beginner
What happens if an error occurs inside the try block?
If an error happens inside the try block, the code stops running there and jumps to the catch block where you can handle the error safely.
Click to reveal answer
beginner
Show a simple example of try-catch in Node.js to handle a synchronous error.
try {
const result = JSON.parse('invalid json');
} catch (error) {
console.log('Caught an error:', error.message);
}Click to reveal answer
intermediate
Why can't try-catch catch errors from asynchronous code like setTimeout or promises?
Because asynchronous code runs later, outside the current try-catch block's scope. Errors happen after the try-catch has finished, so they need special handling like .catch() or async/await with try-catch.
Click to reveal answer
What does a try-catch block catch in Node.js?
✗ Incorrect
Try-catch blocks only catch synchronous errors that happen immediately in the code inside the try block.
Where does the program jump when an error occurs inside a try block?
✗ Incorrect
When an error occurs, the program jumps to the catch block to handle the error.
Which of these errors will NOT be caught by try-catch?
✗ Incorrect
Errors in asynchronous callbacks like setTimeout happen later and are not caught by the surrounding try-catch.
What is the correct syntax to catch errors in synchronous code?
✗ Incorrect
The try-catch syntax requires try first, then catch with an error parameter.
If you want to handle errors from a promise, what should you use instead of try-catch?
✗ Incorrect
Promises handle errors with .catch() or async/await combined with try-catch for asynchronous error handling.
Explain how try-catch works for synchronous errors in Node.js and why it cannot catch asynchronous errors.
Think about when the error happens in relation to the try-catch block.
You got /5 concepts.
Write a simple Node.js code example using try-catch to handle a synchronous error from JSON parsing.
Use JSON.parse with a wrong string inside try.
You got /3 concepts.