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
- The code inside
tryis executed first. usernamehas not been declared.- JavaScript generates an error.
- Instead of stopping the entire program, control moves to
catch. - 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
usercontainsnull.- JavaScript cannot access
.namefromnull. - This causes a
TypeError. - The
catchblock handles the error. error.nametells 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
checkAge()receives an age.- The
ifstatement checks whether the age is below 18. throwmanually creates an error.- The error is caught by
catch. error.messagedisplays 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
- The function receives an input.
typeofchecks the data type."5"is a string, not a number.- Therefore, the condition becomes true.
throw new TypeError()creates an appropriate error.catchhandles 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
numberis set to10.- The condition checks whether it is greater than
5. - The condition is true.
throw new Error()creates an error.error.namegives the error type.error.messagegives 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
- The function receives username and password.
- The username is checked first.
- The password length is checked next.
- If the password has fewer than 8 characters, an error is thrown.
catchreceives that error.- 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
divideNumbers()receives two values.typeofchecks whether both values are numbers.- If either value is not a number, a
TypeErroris thrown. - The second condition checks for division by zero.
- If
bis0, an error is thrown. tryattempts to perform the calculation.catchhandles any error.finallyruns after the error handling is completed.- This creates a safer and more predictable program.
Key Takeaways
- Errors are problems that occur while JavaScript executes code.
trycontains code that might produce an error.catchhandles an error.finallyruns aftertryorcatch.throwallows you to create an error manually.Errorcreates a general error.TypeErroris useful when a value has an unexpected type.error.namegives the error type.error.messagegives 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.
