No matter how good you are at programming, scripts can contain errors. They may occur because of mistakes, unexpected user input, or erroneous server responses.
By default, if an error occurs, JavaScript stops execution and prints the error to the console. Error handling allows you to catch these errors and execute alternative code (like showing a friendly message) instead of crashing the application.
The try statement allows you to define a block of code to be tested for errors while it is being
executed.
The catch statement allows you to define a block of code to be executed if an error occurs in
the try block.
try {
// Code that might fail
let result = someUndefinedFunction();
document.write("This will not run");
} catch (error) {
// Code to handle the error
document.write("An error occurred: " + error.message);
}
The finally statement lets you execute code, after try and catch, regardless of the result. This
is useful for cleanup tasks (like closing a file or hiding a loading spinner).
try {
document.write("Trying...");
throw new Error("Something went wrong!");
} catch (error) {
document.write("Caught: " + error.message);
} finally {
document.write("Finally: This runs no matter what.");
}
The throw statement allows you to create a custom error. You can throw a string, a number, a
boolean, or an object.
function divide(a, b) {
if (b === 0) {
throw new Error("Cannot divide by zero!");
}
return a / b;
}
try {
document.write(divide(10, 0));
} catch (e) {
console.error("Error:", e.message);
}
Try entering a value below. If it's empty, not a number, or too low/high, an error will be thrown and caught.
let ageInput = document.getElementById("ageInput");
let checkBtn = document.getElementById("checkBtn");
let errorOutput = document.getElementById("errorOutput");
checkBtn.addEventListener("click", function() {
try {
errorOutput.textContent = ""; // Clear previous message
let age = Number(ageInput.value);
if(ageInput.value.trim() == "") throw new Error("Input is empty");
if(isNaN(age)) throw new Error("Please enter a valid number");
if(age < 18) throw new Error("You must be 18 or older");
if(age > 100) throw new Error("Age is too high");
errorOutput.textContent = "Access Granted";
errorOutput.style.color = "green";
} catch(e) {
errorOutput.textContent = e.message;
errorOutput.style.color = "red";
}
});
| Feature | Description |
|---|---|
try |
Block of code to test for errors. |
catch |
Block of code to execute if an error occurs. |
throw |
Create custom error messages. |
finally |
Block of code that runs regardless of the result. |
new Error("message")) and
handle them using try...catch to prevent your application from crashing unexpectedly.
Test your understanding of JavaScript Error Handling.
try...catch to handle errors.try block containing code that parses an invalid JSON string (e.g., "{ invalid json }").catch block to handle the potential error.catch block, log a custom error message to the console.try...catch block.try block, intentionally call an undefined function to trigger an error.catch block, log the message property of the error object to the console.finally block.finally block.try...catch...finally structure.finally block to show it runs regardless of an error.checkInput that takes a value.Error with the message "Invalid input!".checkPositive(num).try block.catch block and log the error message.