Which of the following best explains why error handling is important in JavaScript programs?
Think about what happens if something goes wrong in a program without any way to handle it.
Error handling allows a program to manage unexpected problems gracefully, so it can keep working or provide useful messages instead of crashing.
What will be the output of the following JavaScript code?
function divide(a, b) {
return a / b;
}
console.log(divide(10, 0));function divide(a, b) { return a / b; } console.log(divide(10, 0));
In JavaScript, dividing a number by zero does not throw an error but returns a special value.
JavaScript returns Infinity when dividing a positive number by zero instead of throwing an error.
What error will this code produce when run?
const obj = null; console.log(obj.name);
const obj = null; console.log(obj.name);
Accessing a property on null causes a specific type of error in JavaScript.
Trying to access a property on null throws a TypeError because null is not an object.
Which of the following is NOT a benefit of using try-catch blocks in JavaScript?
Think about what try-catch blocks do and what they do not do.
Try-catch blocks help manage errors but do not fix the errors automatically; fixing requires programmer action.
What will be the output of this JavaScript code?
function test() {
try {
console.log('Start');
throw new Error('Oops');
} catch (e) {
console.log('Caught:', e.message);
return 'From catch';
} finally {
console.log('Finally block');
return 'From finally';
}
}
console.log(test());function test() { try { console.log('Start'); throw new Error('Oops'); } catch (e) { console.log('Caught:', e.message); return 'From catch'; } finally { console.log('Finally block'); return 'From finally'; } } console.log(test());
Remember that a return in finally overrides previous returns.
The finally block runs after catch and its return overrides the catch return, so the function returns 'From finally'.