Jump into concepts and practice - no test required
or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
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?
ANo errors
BSynchronous errors
CBoth synchronous and asynchronous errors
DAsynchronous errors
✗ 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?
ATo the catch block
BTo the next line after try-catch
CTo the finally block
DIt crashes immediately
✗ 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?
AError thrown by JSON.parse with invalid input
BError thrown inside the try block
CError thrown inside a setTimeout callback
DError thrown by a function called inside try
✗ 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?
JSON.parse throws an error if input is invalid, so we must catch it to avoid crashing.
Step 2: Check each option's error handling
try {
return JSON.parse(input);
} catch (e) {
return null;
} uses try-catch correctly and returns null on error. if (JSON.parse(input)) {
return JSON.parse(input);
} else {
return null;
} does not catch errors, causing crash. try {
JSON.parse(input);
} catch {
return null;
} misses error parameter in catch and does not return parsed value. return JSON.parse(input) || null; does not catch errors and will crash on invalid input.