Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to catch errors using try-catch.
Javascript
try { console.log('Start'); [1] console.log('End'); } catch (error) { console.log('Error caught'); }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
π‘ Hint
Common Mistakes
Using console.log instead of throw to create an error.
β Incorrect
The throw statement creates an error that is caught by catch.
2fill in blank
mediumComplete the code to handle errors and show a message.
Javascript
function divide(a, b) {
try {
if (b === 0) {
[1]
}
return a / b;
} catch (e) {
return e.message;
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
π‘ Hint
Common Mistakes
Using console.log instead of throw to signal an error.
β Incorrect
Throwing an error with a message lets the catch block handle it properly.
3fill in blank
hardFix the error in the code to properly catch exceptions.
Javascript
try { JSON.parse('invalid json'); } [1] (e) { console.log('Parsing failed'); }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
π‘ Hint
Common Mistakes
Using
error or finally instead of catch.β Incorrect
The catch keyword is required to catch errors thrown in try.
4fill in blank
hardFill both blanks to handle errors and always run cleanup code.
Javascript
try { let data = JSON.parse(input); process(data); } [1] (err) { console.error('Error:', err.message); } [2] { console.log('Cleanup done'); }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
π‘ Hint
Common Mistakes
Using
throw or error keywords incorrectly.β Incorrect
catch handles errors, finally runs code regardless of errors.
5fill in blank
hardFill all three blanks to create a function that safely parses JSON and returns null on error.
Javascript
function safeParse(jsonString) {
try {
return [1](jsonString);
} [2] (e) {
console.warn('Invalid JSON');
return [3];
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
π‘ Hint
Common Mistakes
Using
throw inside catch instead of returning null.β Incorrect
The function tries to parse JSON. If it fails, catch runs and returns null.