This article is about the try…catch…finally statement in JavaScript.
Overview
Try…catch…finally is a JavaScript feature that helps handle errors in code. It allows developers to attempt a risky operation in the try block, and if an error occurs, catch it in the catch block and handle it gracefully. The finally block (not used often) is executed after the try and catch blocks, regardless of whether an error occurred or not:
try {
// risky operation that requires resource
} catch (error) {
// handle error
} finally {
// cleanup resource, regardless of success or failure
}
Now, it’s time to see some real-world use cases for this.
Examples
Handing Network Requests
When making network requests, there are many factors that can cause errors, such as network connectivity, server errors, or invalid data. Using try…catch…finally can help handle these errors gracefully and prevent the application from crashing.
Example:
const fetchData = async (url) => {
try {
const response = await fetch(url);
const data = await response.json();
console.log(data);
} catch (error) {
console.log('Error fetching data:', error);
} finally {
console.log('Cleanup after fetching data');
}
};
// call the function with a wrong url
fetchData('https://not-a-valid-url.slingacademy.com');
Output:
Error fetching data: TypeError: Failed to fetch
Cleanup after fetching data
Validating User Input
When accepting user input, it’s important to validate the data before processing it to prevent errors. Using try…catch can help catch errors during validation and provide feedback to the user.
Example:
const validateEmail = (email) => {
try {
if (!email.length || email.length === 0) {
throw new Error('Email is required');
}
if (email.indexOf('@') === -1) {
throw new Error('Email must contain "@"');
}
return email;
} catch(error) {
console.log('Invalid email:', error.message);
}
}
validateEmail('test#slingacademy.com');
Output:
Invalid email: Email must contain "@"
The example above is a simplified demo of validating email addresses. To see better email validation approaches, read this article: 3 Ways to Validate an Email Address in JavaScript.
Accessing the browser’s storage
When accessing browser storage, such as local storage or session storage, errors can occur due to permission issues or quota limits. Using try…catch…finally can help handle these errors and clean up any resources used.
Example:
try {
localStorage.setItem('username', 'a random user of Sling Academy');
const username = localStorage.getItem('username');
console.log('Username:', username);
} catch (error) {
console.log('Error accessing local storage:', error);
} finally {
console.log('Cleanup after accessing local storage');
}
Output:
Handling errors with promises
Example:
async function asyncFunction() {
return new Promise((resolve, reject) => {
setTimeout(() => {
reject(new Error('Async function error'));
}, 1000);
});
}
async function executeAsyncFunction() {
try {
const result = await asyncFunction();
console.log('Result:', result);
} catch(error) {
console.log('Error executing async function:', error);
}
}
executeAsyncFunction();
Output:
Error executing async function: Error: Async function error
Afterword
These are real-world examples that show how try…catch…finally can be used to handle errors and ensure the smooth operation of JavaScript code. If you have any questions, please leave comments. Happy coding!