Bird
Raised Fist0
Node.jsframework~20 mins

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

Choose your learning style10 modes available

Start learning this pattern below

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
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.

Practice

(1/5)
1. What is the main purpose of using try-catch in Node.js?
easy
A. To handle errors that happen during code execution without stopping the program
B. To speed up the execution of asynchronous code
C. To declare variables that are only used inside a block
D. To format output text in the console

Solution

  1. Step 1: Understand the role of try-catch

    Try-catch is used to catch errors that happen during the running of code so the program can continue safely.
  2. Step 2: Eliminate unrelated options

    Options about speeding asynchronous code, declaring variables, or formatting output do not relate to error handling.
  3. Final Answer:

    To handle errors that happen during code execution without stopping the program -> Option A
  4. Quick Check:

    Error handling = D [OK]
Hint: Try-catch is for catching errors, not for speed or formatting [OK]
Common Mistakes:
  • Thinking try-catch speeds up code
  • Confusing try-catch with variable declaration
  • Using try-catch to format output
2. Which of the following is the correct syntax to catch synchronous errors in Node.js?
easy
A. catch { /* code */ } try (error) { /* handle error */ }
B. try { /* code */ } catch (error) { /* handle error */ }
C. try: { /* code */ } except (error) { /* handle error */ }
D. try { /* code */ } catch error { /* handle error */ }

Solution

  1. Step 1: Recall correct try-catch syntax

    The correct syntax uses try { ... } catch (error) { ... } with parentheses around the error variable.
  2. Step 2: Identify syntax errors in other options

    Options A, B, and D have wrong keywords or missing parentheses, which cause syntax errors.
  3. Final Answer:

    try { /* code */ } catch (error) { /* handle error */ } -> Option B
  4. Quick Check:

    Correct try-catch syntax = C [OK]
Hint: Remember catch always needs parentheses around error [OK]
Common Mistakes:
  • Omitting parentheses in catch
  • Using wrong keywords like except
  • Swapping try and catch blocks
3. What will be the output of this code?
try {
  throw new Error('Oops!');
  console.log('This will not run');
} catch (e) {
  console.log('Caught:', e.message);
}
medium
A. Caught: Oops!
B. This will not run
C. Error: Oops!
D. No output

Solution

  1. Step 1: Understand throw inside try block

    The throw statement immediately stops normal execution and jumps to catch.
  2. Step 2: Check catch block output

    The catch block logs 'Caught:' plus the error message 'Oops!'. The line after throw is skipped.
  3. Final Answer:

    Caught: Oops! -> Option A
  4. Quick Check:

    throw triggers catch output = B [OK]
Hint: Throw stops try block; catch runs next [OK]
Common Mistakes:
  • Expecting code after throw to run
  • Confusing error object with message
  • Thinking no output appears
4. Identify the error in this code snippet:
try {
  console.log('Start');
  throw 'Error happened';
} catch e {
  console.log('Caught:', e);
}
medium
A. Console.log syntax is wrong
B. Throw cannot use string errors
C. Missing parentheses around catch parameter
D. Try block must not contain throw

Solution

  1. Step 1: Check catch syntax

    The catch block must have parentheses around the error variable, like catch (e).
  2. Step 2: Verify other parts

    Throwing a string is allowed, console.log syntax is correct, and throw is valid inside try.
  3. Final Answer:

    Missing parentheses around catch parameter -> Option C
  4. Quick Check:

    Catch needs parentheses = A [OK]
Hint: Catch always needs parentheses around error variable [OK]
Common Mistakes:
  • Omitting parentheses in catch
  • Thinking throw can't use strings
  • Misreading console.log syntax
5. You want to safely parse JSON input that might be invalid. Which code correctly uses try-catch to handle errors and return null if parsing fails?
hard
A. return JSON.parse(input) || null;
B. if (JSON.parse(input)) { return JSON.parse(input); } else { return null; }
C. try { JSON.parse(input); } catch { return null; }
D. try { return JSON.parse(input); } catch (e) { return null; }

Solution

  1. Step 1: Understand JSON.parse error behavior

    JSON.parse throws an error if input is invalid, so we must catch it to avoid crashing.
  2. 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.
  3. Final Answer:

    try { return JSON.parse(input); } catch (e) { return null; } -> Option D
  4. Quick Check:

    Use try-catch to catch JSON errors = A [OK]
Hint: Wrap JSON.parse in try-catch to handle invalid input safely [OK]
Common Mistakes:
  • Not using try-catch around JSON.parse
  • Ignoring catch error parameter
  • Assuming JSON.parse returns null on error