Skip to content

J078 Custom Error Handling in JavaScript

A task aimed at understanding how to throw and handle custom errors in JavaScript based on specific conditions.

Create a file named app.js and adhere to the following guidelines:

  • Start with “use strict”.
  • Create a function named printString that accepts a single parameter, str.
  • The function should check the length of str.
  • If the length of str is less than 5 characters, throw a new error with the message “String too short”.
  • If the string length is adequate, print the string to the console.

Testing the Function

  • Call printString with various strings to test the functionality.
  • Use a try-catch block to handle any errors thrown by the function.
  • In the catch block, log the error message to the console.
  • Include at least one string that is shorter than 5 characters to trigger the error.

Reflecting on Custom Errors

  • Understand how throwing custom errors based on specific conditions can enhance the robustness of your code.
  • Notice how the program handles both successful and error scenarios.
Example Usage
"use strict";

function printString(str) {
    if (str.length < 5) {
        throw new Error("String too short");
    }
    console.log(str);
}

try {
    printString("Hello World"); // Prints "Hello World"
} catch (error) {
    console.log(error.message);
}

try {
    printString("Hi"); // Error caught here
} catch (error) {
    console.log(error.message);
}

try {
    printString("Welcome"); // Prints "Welcome"
} catch (error) {
    console.log(error.message);
}