JavaScript
Summary - Errors
Safely handle a division by zero using try/catch/finally and throw.
Summary - Errors
In this group you learned the basics of error handling. try holds risky code, catch catches the error, finally runs in every case. With throw new Error("message") you can throw your own error and catch it with catch. The Error object's message, name and stack properties give the error details.
Now you will combine all these tools and write a function that safely handles a division by zero. You will throw the error with throw and catch and clean up with try...catch...finally. This is the core of error handling in real applications.
Exercise Handle a division by zero
Define a function called divide. It should take a and b parameters. In the body open a try block. Inside it check with if (b === 0); when it holds call throw new Error("Division by zero"), otherwise return a / b. In a catch (e) block call console.error(e.message) and return null. Then call divide(10, 0).
Show example solution
function divide(a, b) {
try {
if (b === 0) {
throw new Error("Division by zero");
}
return a / b;
} catch (e) {
console.error(e.message);
return null;
}
}
divide(10, 0);
Exercise Full handling with try/catch/finally
Add a finally block to the previous divide function. In the finally block call console.log("Operation complete"). The try, catch and finally blocks must appear in order. Then call divide(10, 0).
Show example solution
function divide(a, b) {
try {
if (b === 0) {
throw new Error("Division by zero");
}
return a / b;
} catch (e) {
console.error(e.message);
return null;
} finally {
console.log("Operation complete");
}
}
divide(10, 0);
Test yourself
-
Match error handling concepts
- try
- Risky code block
- catch
- Catches the error
- finally
- Always runs
- throw
- Throws an error
- Error
- Error object
-
Complete the finally block
function divide(a, b) {
try {
if (b === 0) throw new Error("Division by zero");
return a / b;
} catch (e) {
console.error(e.message);
return null;
} ____ {
console.log("Operation complete");
}
}
Show answer
function divide(a, b) {
try {
if (b === 0) throw new Error("Division by zero");
return a / b;
} catch (e) {
console.error(e.message);
return null;
} finally {
console.log("Operation complete");
}
}
Next lesson: What is debugging?