- -- operator
- -= operator
- ++ operator
- += operator
- Accessing and setting content
- Array length
- Arrays
- Between braces
- Booleans
- Braces
- Callback function
- Calling the function
- Class
- Closure
- Code block
- Conditions
- Console
- Constructor
- Creating a p element
- Data types
- Destructuring
- Else
- Else if
- Equals operator
- Error Handling
- ES6
- Event loop
- Events
- Extend
- Fetch API
- Filter
- For loop
- Function
- Function name
- Greater than
- Head element
- Hoisting
- If statement
- JSON
- Less than
- Local storage
- Map
- Methods
- Module
- Numbers
- Overriding methods
- Parameters
- Promises
- Reduce
- Regular expressions
- Removing an element
- Replace
- Scope
- Session storage
- Sort
- Splice
- String
- Substring
- Template literals
- Tile
- Type conversion
- While loop
JAVASCRIPT
JavaScript Error Handling: Syntax, Usage, and Examples
JavaScript error handling is the process of managing and responding to runtime errors in your code. Effective error handling in JavaScript prevents crashes, improves user experience, and makes debugging easier. JavaScript provides built-in mechanisms to catch, throw, and handle errors gracefully.
How to Use JavaScript Error Handling
JavaScript provides the try...catch
statement to catch and handle errors without stopping script execution.
Basic Syntax
try {
// Code that may throw an error
} catch (error) {
// Code to handle the error
} finally {
// Code that always runs, regardless of an error
}
try
– Runs the code block and watches for errors.catch
– Executes if an error occurs intry
, capturing the error object.finally
– Runs code whether or not an error occurred (optional).
Throwing Custom Errors
You can manually throw an error using the throw
statement.
function checkAge(age) {
if (age < 18) {
throw new Error("You must be 18 or older.");
}
return "Access granted";
}
try {
console.log(checkAge(16));
} catch (error) {
console.log("Error:", error.message);
}
When to Use JavaScript Error Handling
Error handling in JavaScript is essential in situations where unexpected issues might occur. Here are three common use cases:
- Handling API and network errors – If an API request fails, error handling can retry the request or display an error message.
- Validating user input – If a user enters invalid data, error handling can prompt them to fix it instead of breaking the application.
- Preventing application crashes – When dealing with unexpected values or missing data, structured error handling ensures the app continues running.
Examples of JavaScript Error Handling
Catching Errors in Asynchronous Code
When working with asynchronous functions and promises, errors can be handled using .catch()
.
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error("Error fetching data:", error.message));
If the fetch request fails (e.g., no internet connection), the .catch()
method handles the error gracefully.
Handling Errors with async
and await
For cleaner error handling in asynchronous functions, use try...catch
.
async function fetchData() {
try {
const response = await fetch("https://jsonplaceholder.typicode.com/posts/1");
const data = await response.json();
console.log(data);
} catch (error) {
console.error("Error fetching data:", error.message);
}
}
fetchData();
This prevents unhandled promise rejections and allows a structured response to errors.
Using finally
to Clean Up
The finally
block ensures cleanup actions always run, even if an error occurs.
function processTask() {
try {
console.log("Processing...");
throw new Error("Something went wrong!");
} catch (error) {
console.error("Caught error:", error.message);
} finally {
console.log("Task completed (cleaning up resources).");
}
}
processTask();
Learn More About JavaScript Error Handling
Different Types of JavaScript Errors
JavaScript errors fall into different categories:
-
ReferenceError – Trying to use a variable that hasn’t been defined.
console.log(nonExistentVar); // ReferenceError
-
TypeError – Calling a method on an undefined or incorrect data type.
let num = 42; num.toUpperCase(); // TypeError: num.toUpperCase is not a function
-
SyntaxError – Writing invalid JavaScript syntax.
javascript CopyEdit console.log("Hello; // SyntaxError: missing closing quote
-
RangeError – Exceeding the allowed range of values.
function recurse() { return recurse(); } recurse(); // RangeError: Maximum call stack size exceeded
Using Error
Object Properties
The Error
object provides useful properties when handling errors.
try {
throw new Error("Custom error message");
} catch (error) {
console.log(error.name); // "Error"
console.log(error.message); // "Custom error message"
console.log(error.stack); // Stack trace for debugging
}
Creating Custom Error Classes
For better error categorization, create custom error classes by extending the Error
object.
class ValidationError extends Error {
constructor(message) {
super(message);
this.name = "ValidationError";
}
}
try {
throw new ValidationError("Invalid input!");
} catch (error) {
console.log(error.name); // "ValidationError"
console.log(error.message); // "Invalid input!"
}
Global Error Handling with window.onerror
In browsers, you can catch uncaught errors globally.
window.onerror = function (message, source, lineno, colno, error) {
console.error(`Error: ${message} at ${source}:${lineno}:${colno}`);
};
Debugging Errors in JavaScript
When debugging errors:
- Use
console.log()
to track variable values. - Use
console.error()
for errors to stand out in the console. - Check browser developer tools (
F12
orCmd + Opt + I
).
JavaScript error handling ensures smooth program execution by catching and responding to unexpected errors. Use try...catch
, throw
, and finally
to manage errors effectively.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.