0
0
Javascriptprogramming~10 mins

Why error handling is required in Javascript - Test Your Understanding

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete 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'
Abreak
Bconsole.log('No error')
Creturn 'Done'
Dthrow new Error('Oops!')
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using console.log instead of throw to create an error.
2fill in blank
medium

Complete 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'
Areturn 'Error'
Bthrow new Error('Cannot divide by zero')
Cbreak
Dconsole.log('Divide by zero')
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using console.log instead of throw to signal an error.
3fill in blank
hard

Fix 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'
Acatch
Berror
Cfinally
Dthrow
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using error or finally instead of catch.
4fill in blank
hard

Fill 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'
Acatch
Bfinally
Cthrow
Derror
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using throw or error keywords incorrectly.
5fill in blank
hard

Fill 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'
AJSON.parse
Bcatch
Cnull
Dthrow
Attempts:
3 left
πŸ’‘ Hint
Common Mistakes
Using throw inside catch instead of returning null.