Skip to content

J075 Understanding Exception Handling

A task focused on practicing exception handling in JavaScript by using a provided function.

Create an app.js file and follow these instructions:

  • Start with “use strict”.

Provided Function: addNumbers

  • A function addNumbers is provided. It takes two parameters, a and b.
  • The function throws an error if either a or b is negative, with the message “Negative numbers are not allowed”.
  • If both numbers are positive, the function returns their sum.
function addNumbers(a, b) {
    if (a < 0 || b < 0) {
        throw new Error("Negative numbers are not allowed");
    }
    return a + b;
}

Your Task: Call the Provided Function

  • Call the addNumbers function with different pairs of numbers. Include both valid cases and at least one case where a negative number is passed.
  • For each call, use a try-catch block to handle any potential errors.
  • In the catch block, log the error message to the console.
  • Observe the output in the console for each call.

Understanding Exception Handling

  • Reflect on how using try-catch blocks helps in managing errors and maintaining the flow of the program even when exceptions occur.
Example Usage
"use strict";

function addNumbers(a, b) {
    if (a < 0 || b < 0) {
        throw new Error("Negative numbers are not allowed");
    }
    return a + b;
}

try {
    console.log(addNumbers(5, 5)); // 10
} catch (error) {
    console.log(error.message);
}

try {
    console.log(addNumbers(-3, 6)); // Error caught here
} catch (error) {
    console.log(error.message);
}

try {
    console.log(addNumbers(4, -2)); // Error caught here
} catch (error) {
    console.log(error.message);
}