Topic Overview and Actualization

Welcome to the realm of exceptions in JavaScript functions! In this journey, you will learn how exceptions operate within a function, how to handle these unexpected events using try-catch, and how to rethrow exceptions. We will also examine the consequences of unhandled exceptions. This knowledge will aid you in crafting robust JavaScript functions.

JavaScript Functions and Exceptions

We will delve into the workings of exceptions inside functions. Exceptions can be thrown from any location in a function using the throw keyword. For instance:

function validateBaseID(baseID) {
  // If the ID is invalid, throw an exception
  if (baseID <= 0) {
    throw new Error("Invalid ID!");
  }
}

In this scenario, an exception is thrown if the baseID is invalid. An exception interrupts normal function execution until it is caught.

Alternatively, we could throw new Error("Invalid ID!"); - in that case, the error message when catching the error will be accessible in the message field.

Catch and Rethrow Exceptions within JavaScript Functions

The common pattern in functions is catching an exception, implementing a handling action (like logging or processing the error case), and then optionally rethrowing it if we need to allow the exception to signal an issue to the function's caller. See the following example:

function inspectAndDeliverCargo(baseID) {
  try {
    validateBaseID(baseID);  // If an exception is thrown, it gets caught here
    console.log('Cargo inspection complete...');
  } catch (exception) {
    console.log('Error with cargo inspection: ', exception.message);
    throw exception;  // rethrowing the caught exception, the caller will receive it
  }
}

try {
  inspectAndDeliverCargo(-1);
} catch (ex) {
  console.log("Cargo delivery failed! Reason: " + ex.message);
}
// Prints:
// Error with cargo inspection: Invalid ID!
// Cargo delivery failed! Reason Invalid ID!

In this case, if the validateBaseID() function throws an exception, it's caught and then rethrown to be handled by the caller.

Understanding the Impacts of Uncaught Exceptions

Uncaught exceptions halt function execution and propagate up to the caller. If not intercepted, they continue to ascend to the global code. If they remain uncaught, the script will terminate.

function deliverCargo(baseID) {
  validateBaseID(baseID);  // Function throws an exception if baseID is invalid
  console.log('Delivery started'); // This will not be executed if an exception is thrown above
}

deliverCargo(-1);  // Uncaught Invalid ID!

In this situation, our code abruptly stops with an uncaught exception message. This could be a potentially fatal scenario, akin to a spacecraft malfunction jeopardizing the entire mission.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal