Challenge - 5 Problems
Try-Catch Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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); }
Attempts:
2 left
💡 Hint
Think about what happens when JSON.parse receives invalid input.
✗ Incorrect
JSON.parse throws a SyntaxError when given invalid JSON. The try-catch catches this error and logs its message.
❓ component_behavior
intermediate1: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?
Attempts:
2 left
💡 Hint
Remember how asynchronous errors are handled differently in Node.js.
✗ Incorrect
Try-catch blocks catch errors thrown synchronously inside the try block. Asynchronous errors require other handling methods.
🔧 Debug
advanced2: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); }
Attempts:
2 left
💡 Hint
Think about how try-catch works with asynchronous callbacks.
✗ Incorrect
The error is thrown asynchronously inside setTimeout, outside the try block's synchronous execution, so it is uncaught and crashes the program.
📝 Syntax
advanced1:30remaining
Which option shows correct try-catch syntax in Node.js?
Select the option that uses valid try-catch syntax to handle synchronous errors.
Attempts:
2 left
💡 Hint
Check the parentheses and braces around catch and error variable.
✗ Incorrect
Option D uses correct syntax: catch keyword followed by parentheses with error variable, then braces for block.
❓ state_output
expert2: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'; }
Attempts:
2 left
💡 Hint
Remember that code after throw inside try is skipped, but finally always runs.
✗ Incorrect
The throw stops execution inside try after 'start-'. Catch adds 'caught-'. Finally adds 'finally'. So result is 'start-caught-finally'.