17.4. Exercises: Exceptions

17.4.1. Zero Division: Throw

Write a function called divide that takes two parameters: a numerator and a denominator.

Your function should return the result of numerator / denominator.

However, if denominator is zero you should throw the error, "Attempted to divide by zero."

Note

Hint: You can use an if / throw statement to complete this exercise.

Code your function at this repl.it.

Check your solution.

17.4.2. Test Student Labs

A teacher has created a gradeLabs function that verifies if student programming labs work. This function loops over an array of JavaScript objects that should contain a student property and runLab property.

The runLab property is expected to be a function containing the student's code. The runLab function is called and the result is compared to the expected result. If the result and expected result don't match, then the lab is considered a failure.

 1 function gradeLabs(labs) {
 2   for (let i=0; i < labs.length; i++) {
 3      let lab = labs[i];
 4      let result = lab.runLab(3);
 5      console.log(`${lab.student} code worked: ${result === 27}`);
 6   }
 7 }
 8
 9let studentLabs = [
10   {
11      student: 'Carly',
12      runLab: function (num) {
13         return Math.pow(num, num);
14      }
15   },
16   {
17      student: 'Erica',
18      runLab: function (num) {
19         return num * num;
20      }
21   }
22];
23
24gradeLabs(studentLabs);

The gradeLabs function works for the majority of cases. However, what happens if a student named their function incorrectly? Run gradeLabs and pass it studentLabs2 as defined below.

 1let studentLabs2 = [
 2   {
 3      student: 'Blake',
 4      myCode: function (num) {
 5         return Math.pow(num, num);
 6      }
 7   },
 8   {
 9      student: 'Jessica',
10      runLab: function (num) {
11         return Math.pow(num, num);
12      }
13   },
14   {
15      student: 'Mya',
16      runLab: function (num) {
17         return num * num;
18      }
19   }
20];
21
22gradeLabs(studentLabs2);

Upon running the second example, the teacher gets TypeError: lab.runLab is not a function.

Add a try/catch block inside of gradeLabs to catch an exception if the runLab property is not defined. If the exception is thrown, result should be set to the text "Error thrown".