0
0
Javascriptprogramming~20 mins

Try–catch block in Javascript - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Try–catch Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of try–catch with thrown error
What will be printed to the console when this code runs?
Javascript
try {
  console.log('Start');
  throw new Error('Oops!');
  console.log('End');
} catch (e) {
  console.log('Caught:', e.message);
}
ACaught: Oops!
BStart\nEnd\nCaught: Oops!
CStart\nCaught: Oops!
DStart\nEnd
Attempts:
2 left
💡 Hint
Remember that code after throw inside try does not run.
Predict Output
intermediate
2:00remaining
Value of variable after try–catch
What is the value of variable x after this code runs?
Javascript
let x = 0;
try {
  x = 5;
  throw 'error';
  x = 10;
} catch (e) {
  x = 20;
}
A20
B5
C10
D0
Attempts:
2 left
💡 Hint
Check which assignments run before and after the throw.
Predict Output
advanced
2:30remaining
Output with nested try–catch and finally
What will this code print to the console?
Javascript
try {
  console.log('Outer try');
  try {
    console.log('Inner try');
    throw 'error';
  } catch (e) {
    console.log('Inner catch');
    throw 'new error';
  } finally {
    console.log('Inner finally');
  }
} catch (e) {
  console.log('Outer catch');
} finally {
  console.log('Outer finally');
}
AOuter try\nInner try\nInner catch\nOuter catch\nOuter finally
BOuter try\nInner try\nInner catch\nOuter catch\nInner finally\nOuter finally
COuter try\nInner try\nInner finally\nInner catch\nOuter catch\nOuter finally
DOuter try\nInner try\nInner catch\nInner finally\nOuter catch\nOuter finally
Attempts:
2 left
💡 Hint
Remember finally always runs after try or catch blocks.
Predict Output
advanced
2:00remaining
Error type caught in catch block
What will be the output of this code?
Javascript
try {
  JSON.parse('invalid json');
} catch (e) {
  console.log(e instanceof SyntaxError);
  console.log(e instanceof Error);
  console.log(e.name);
}
Afalse\ntrue\nSyntaxError
Btrue\ntrue\nSyntaxError
Ctrue\nfalse\nError
Dfalse\nfalse\nError
Attempts:
2 left
💡 Hint
Check the type of error JSON.parse throws on invalid input.
🧠 Conceptual
expert
2:30remaining
Behavior of try–catch with asynchronous code
Consider this code snippet. Which statement is true about the output?
Javascript
try {
  setTimeout(() => {
    throw new Error('Async error');
  }, 0);
} catch (e) {
  console.log('Caught:', e.message);
}
console.log('End');
APrints only 'End' and the error is uncaught
BPrints 'Caught: Async error' then 'End'
CThrows SyntaxError before printing anything
DPrints 'End' then 'Caught: Async error'
Attempts:
2 left
💡 Hint
Remember how try–catch works with asynchronous callbacks.