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.
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:
JavaScript1function validateBaseID(baseID) { 2 // If the ID is invalid, throw an exception 3 if (baseID <= 0) { 4 throw new Error("Invalid ID!"); 5 } 6}
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.
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:
JavaScript1function inspectAndDeliverCargo(baseID) { 2 try { 3 validateBaseID(baseID); // If an exception is thrown, it gets caught here 4 console.log('Cargo inspection complete...'); 5 } catch (exception) { 6 console.log('Error with cargo inspection: ', exception.message); 7 throw exception; // rethrowing the caught exception, the caller will receive it 8 } 9} 10 11try { 12 inspectAndDeliverCargo(-1); 13} catch (ex) { 14 console.log("Cargo delivery failed! Reason: " + ex.message); 15} 16// Prints: 17// Error with cargo inspection: Invalid ID! 18// 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.
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.
JavaScript1function deliverCargo(baseID) { 2 validateBaseID(baseID); // Function throws an exception if baseID is invalid 3 console.log('Delivery started'); // This will not be executed if an exception is thrown above 4} 5 6deliverCargo(-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.
Great work! Now, you are adept at handling exceptions. You've learned how to raise, catch, and rethrow them within functions, and you're aware of the impact of unhandled exceptions.
Let's reinforce this knowledge through hands-on exercises. These tasks will simulate real-world scenarios, which will help you to practice and fortify these skills. So, ready, set, code!