Challenge - 5 Problems
Try–catch Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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); }
Attempts:
2 left
💡 Hint
Remember that code after throw inside try does not run.
✗ Incorrect
The code prints 'Start' first. Then the error is thrown, so 'End' is skipped. The catch block runs and prints 'Caught: Oops!'.
❓ Predict Output
intermediate2: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; }
Attempts:
2 left
💡 Hint
Check which assignments run before and after the throw.
✗ Incorrect
x is set to 5, then error is thrown, so x=10 is skipped. Catch block sets x to 20.
❓ Predict Output
advanced2: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'); }
Attempts:
2 left
💡 Hint
Remember finally always runs after try or catch blocks.
✗ Incorrect
The inner try throws 'error', caught by inner catch which throws 'new error'. Inner finally runs next. Outer catch catches 'new error'. Outer finally runs last.
❓ Predict Output
advanced2: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); }
Attempts:
2 left
💡 Hint
Check the type of error JSON.parse throws on invalid input.
✗ Incorrect
JSON.parse throws a SyntaxError, which is also an Error. So instanceof SyntaxError and instanceof Error are both true. The name is 'SyntaxError'.
🧠 Conceptual
expert2: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');
Attempts:
2 left
💡 Hint
Remember how try–catch works with asynchronous callbacks.
✗ Incorrect
The throw inside setTimeout runs asynchronously, outside the try block's scope. So catch does not catch it. 'End' prints first. The error is uncaught and will appear as an unhandled exception.