0
0
Node.jsframework~20 mins

Try-catch for synchronous errors in Node.js - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Try-Catch Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this Node.js code with try-catch?
Consider this code snippet that uses try-catch to handle synchronous errors. What will it print to the console?
Node.js
try {
  JSON.parse('invalid json');
  console.log('Parsed successfully');
} catch (error) {
  console.log('Caught error:', error.message);
}
ACaught error: Unexpected token i in JSON at position 0
BParsed successfully
CCaught error: SyntaxError
DNo output, program crashes
Attempts:
2 left
💡 Hint
Think about what happens when JSON.parse receives invalid input.
component_behavior
intermediate
1:30remaining
How does try-catch behave with synchronous errors in Node.js?
Which statement best describes how try-catch handles synchronous errors in Node.js?
AIt catches both synchronous and asynchronous errors automatically.
BIt only catches synchronous errors thrown inside the try block.
CIt cannot catch any errors in Node.js.
DIt catches errors only if they are thrown asynchronously.
Attempts:
2 left
💡 Hint
Remember how asynchronous errors are handled differently in Node.js.
🔧 Debug
advanced
2:00remaining
Identify the error in this try-catch usage
What error will this Node.js code produce when run?
Node.js
try {
  setTimeout(() => {
    throw new Error('Async error');
  }, 100);
} catch (e) {
  console.log('Caught:', e.message);
}
ACaught: Async error
BSyntaxError: Unexpected token
CNo output, program crashes with uncaught error
DCaught: undefined
Attempts:
2 left
💡 Hint
Think about how try-catch works with asynchronous callbacks.
📝 Syntax
advanced
1:30remaining
Which option shows correct try-catch syntax in Node.js?
Select the option that uses valid try-catch syntax to handle synchronous errors.
A
try {
  doSomething();
} catch {
  console.log(error);
}
B
try {
  doSomething();
} catch error {
  console.log(error);
}
C
try {
  doSomething();
} catch (error) {
  console.log(error.message
}
D
try {
  doSomething();
} catch (error) {
  console.log(error);
}
Attempts:
2 left
💡 Hint
Check the parentheses and braces around catch and error variable.
state_output
expert
2:30remaining
What is the value of variable 'result' after this try-catch block?
Analyze the following code and determine the final value of 'result'.
Node.js
let result = '';
try {
  result += 'start-';
  throw new Error('fail');
  result += 'end-';
} catch (e) {
  result += 'caught-';
} finally {
  result += 'finally';
}
A"start-caught-finally"
B"start-end-caught-finally"
C"caught-finally"
D"start-finally"
Attempts:
2 left
💡 Hint
Remember that code after throw inside try is skipped, but finally always runs.