0
0
Node.jsframework~5 mins

Try-catch for synchronous errors in Node.js - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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
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
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
What is the correct syntax to catch errors in synchronous code?
Acatch { /* handle error */ } try { /* code */ }
Btry { /* code */ } then { /* handle error */ }
Ctry { /* code */ } finally { /* handle error */ }
Dtry { /* code */ } catch (error) { /* handle error */ }
If you want to handle errors from a promise, what should you use instead of try-catch?
A.catch() method or async/await with try-catch
BAnother try-catch block
CsetTimeout
Dconsole.log
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.