JavaScript Error Handling Practice Questions with solutions

Introductions

JavaScript errors can stop your program from working correctly. Error handling helps you detect errors, prevent unexpected crashes, and show useful messages to users. In this chapter, you will practice try...catch, finally, throw, built-in error types, and custom error handling with easy examples. JavaScript Error Handling practice questions help to understand the concpets.

Question 1: Handle an Error with try...catch

Problem

Create a JavaScript program that intentionally causes an error and handle it using try...catch.

Solution

try {
    console.log(username);
} catch (error) {
    console.log("An error occurred.");
}

Output

An error occurred.

Step-by-step Explanation

  1. The code inside try is executed first.
  2. username has not been declared.
  3. JavaScript generates an error.
  4. Instead of stopping the entire program, control moves to catch.
  5. The error message is displayed.

Question 2: Display the Actual Error Message

Problem

Use the catch block to display the actual JavaScript error message.

Solution

try {
    console.log(username);
} catch (error) {
    console.log(error.message);
}

Output

username is not defined

Step-by-step Explanation

The catch block receives an error object.

catch (error)

The error.message property contains the message describing the error.

You can also display the complete error:

console.log(error);

Question 3: Use finally

Problem

Create a try...catch...finally block and display a message from the finally block.

Solution

try {
    console.log("Trying to run the code");
} catch (error) {
    console.log("An error occurred");
} finally {
    console.log("This code always runs");
}

Output

Trying to run the code
This code always runs

Step-by-step Explanation

A finally block runs after the try or catch block finishes.

The structure is:

try {
    // Code
} catch (error) {
    // Error handling
} finally {
    // Code that runs afterward
}

The finally block is useful for cleanup operations.


Question 4: Handle a TypeError

Problem

Try to call a method on null and handle the resulting error.

Solution

try {
    let user = null;

    console.log(user.name);

} catch (error) {
    console.log("Something went wrong.");
    console.log(error.name);
}

Output

Something went wrong.
TypeError

Step-by-step Explanation

  1. user contains null.
  2. JavaScript cannot access .name from null.
  3. This causes a TypeError.
  4. The catch block handles the error.
  5. error.name tells us the type of error.

Question 5: Use throw to Create Your Own Error

Problem

Check a user’s age. If the age is below 18, manually create an error using throw.

Solution

function checkAge(age) {

    if (age < 18) {
        throw new Error("You must be at least 18 years old.");
    }

    return "Age is valid.";
}

try {

    console.log(checkAge(15));

} catch (error) {

    console.log(error.message);

}

Output

You must be at least 18 years old.

Step-by-step Explanation

  1. checkAge() receives an age.
  2. The if statement checks whether the age is below 18.
  3. throw manually creates an error.
  4. The error is caught by catch.
  5. error.message displays the custom message.

Question 6: Validate a Number with Error Handling

Problem

Create a function that accepts only numbers. If another data type is provided, throw an error.

Solution

function calculateSquare(number) {

    if (typeof number !== "number") {
        throw new TypeError("Input must be a number.");
    }

    return number * number;
}

try {

    console.log(calculateSquare("5"));

} catch (error) {

    console.log(error.name);
    console.log(error.message);

}

Output

TypeError
Input must be a number.

Step-by-step Explanation

  1. The function receives an input.
  2. typeof checks the data type.
  3. "5" is a string, not a number.
  4. Therefore, the condition becomes true.
  5. throw new TypeError() creates an appropriate error.
  6. catch handles the error.

Question 7: Handle JSON Parsing Errors

Problem

Try to convert invalid JSON into a JavaScript object and handle the error.

Solution

const data = '{"name": "Rahul",}';

try {

    const user = JSON.parse(data);

    console.log(user);

} catch (error) {

    console.log("Invalid JSON data.");

}

Output

Invalid JSON data.

Step-by-step Explanation

JSON.parse() converts a JSON string into a JavaScript object.

The following JSON is invalid:

'{"name": "Rahul",}'

There is an extra comma before the closing brace.

Therefore, JSON.parse() throws an error and the catch block handles it.


Question 8: Handle Different Errors with error.name

Problem

Create a program that handles an error and displays its name and message.

Solution

try {

    let number = 10;

    if (number > 5) {
        throw new Error("Number is greater than 5.");
    }

} catch (error) {

    console.log("Error Type:", error.name);
    console.log("Message:", error.message);

}

Output

Error Type: Error
Message: Number is greater than 5.

Step-by-step Explanation

  1. number is set to 10.
  2. The condition checks whether it is greater than 5.
  3. The condition is true.
  4. throw new Error() creates an error.
  5. error.name gives the error type.
  6. error.message gives the error description.

Question 9: Create a Custom Validation Function

Problem

Create a registration function that validates a username and password. Throw an error when either value is invalid.

Solution

function register(username, password) {

    if (username.trim() === "") {
        throw new Error("Username is required.");
    }

    if (password.length < 8) {
        throw new Error(
            "Password must contain at least 8 characters."
        );
    }

    return "Registration successful!";
}

try {

    console.log(
        register("Rahul", "1234")
    );

} catch (error) {

    console.log(error.message);

}

Output

Password must contain at least 8 characters.

Step-by-step Explanation

  1. The function receives username and password.
  2. The username is checked first.
  3. The password length is checked next.
  4. If the password has fewer than 8 characters, an error is thrown.
  5. catch receives that error.
  6. The error message is displayed.

If the input is:

register("Rahul", "javascript123");

The output becomes:

Registration successful!

Question 10: Build a Complete Error Handling Example

Problem

Create a small calculator that:

  • Accepts two numbers.
  • Checks whether both values are numbers.
  • Prevents division by zero.
  • Throws errors when the input is invalid.
  • Uses try...catch...finally.

Solution

function divideNumbers(a, b) {

    if (typeof a !== "number" || typeof b !== "number") {
        throw new TypeError("Both values must be numbers.");
    }

    if (b === 0) {
        throw new Error("Cannot divide by zero.");
    }

    return a / b;
}

try {

    const result = divideNumbers(20, 0);

    console.log("Result:", result);

} catch (error) {

    console.log("Error:", error.message);

} finally {

    console.log("Calculation completed.");

}

Output

Error: Cannot divide by zero.
Calculation completed.

Step-by-step Explanation

  1. divideNumbers() receives two values.
  2. typeof checks whether both values are numbers.
  3. If either value is not a number, a TypeError is thrown.
  4. The second condition checks for division by zero.
  5. If b is 0, an error is thrown.
  6. try attempts to perform the calculation.
  7. catch handles any error.
  8. finally runs after the error handling is completed.
  9. This creates a safer and more predictable program.

Key Takeaways

  • Errors are problems that occur while JavaScript executes code.
  • try contains code that might produce an error.
  • catch handles an error.
  • finally runs after try or catch.
  • throw allows you to create an error manually.
  • Error creates a general error.
  • TypeError is useful when a value has an unexpected type.
  • error.name gives the error type.
  • error.message gives the error description.
  • JSON.parse() can throw an error when given invalid JSON.
  • Error handling makes programs more reliable.
  • Client-side error handling improves the user experience, but it does not replace proper server-side validation.

FAQs

1. What is error handling in JavaScript?

Error handling is the process of detecting and responding to errors without allowing unexpected problems to break the application’s normal flow.

JavaScript commonly uses:

try
catch
finally
throw

2. What is the purpose of try...catch?

try...catch allows you to handle errors that occur while executing a block of code.

try {
    // Code that may cause an error
} catch (error) {
    // Handle the error
}

3. What does throw do in JavaScript?

throw manually generates an exception.

throw new Error("Something went wrong.");

The thrown error can then be handled by a surrounding catch block.

4. What is the purpose of finally?

finally contains code that should run after the try and catch processing.

try {
    console.log("Try");
} catch (error) {
    console.log("Catch");
} finally {
    console.log("Finally");
}

The finally block is useful for cleanup tasks.

5. What is error.message?

error.message contains the descriptive message associated with an error.

try {
    throw new Error("Invalid input.");
} catch (error) {
    console.log(error.message);
}

Output:

Invalid input.

6. What is the difference between Error and TypeError?

Error is a general error type:

throw new Error("Something went wrong.");

TypeError specifically represents an operation involving an inappropriate value type:

throw new TypeError("Expected a number.");

7. Can try...catch catch every JavaScript error?

No. It catches exceptions thrown during execution of the code inside the try block. It does not automatically make every kind of problem in an application disappear, and errors that occur asynchronously generally need to be handled where that asynchronous operation executes.

Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.

Scroll to Top