In JavaScript, error handling is commonly done using the try...catch
statement. The try
block lets you test a block of code for errors, while the catch
block lets you handle the error. Here are a few examples that demonstrate how to use catch
to handle errors in different scenarios:
1. Basic try...catch
try {
// Code that may throw an error
let result = someFunction();
console.log(result);
} catch (error) {
// Code to run if an error occurs
console.log('An error occurred:', error.message);
}
2. Catch with Finally
finally
is an optional block that will execute after the try and catch blocks, regardless of whether an error was thrown or not. It’s often used for cleaning up resources.
try {
// Code that may throw an error
let data = riskyOperation();
console.log(data);
} catch (error) {
// Handle errors
console.error('Error:', error.message);
} finally {
// Cleanup code, runs whether or not an error occurred
console.log('Operation complete.');
}
3. Catch with Error Logging
This example demonstrates logging the error for further investigation while notifying the user in a general manner.
try {
// This function might fail
performCriticalTask();
} catch (error) {
console.error('Error logged:', error);
// Notify user in a user-friendly manner
alert('Something went wrong. Please try again later.');
}
4. Catch with Specific Error Types
Sometimes you might want to handle different types of errors differently. This can be done by checking the type of the error.
try {
// This function might throw several types of errors
processUserInput(input);
} catch (error) {
if (error instanceof TypeError) {
console.error('Type Error:', error.message);
} else if (error instanceof RangeError) {
console.error('Range Error:', error.message);
} else {
console.error('Unexpected Error:', error.message);
}
}
5. Async/Await with Try-Catch
When working with asynchronous code, you can use try...catch
to handle errors in promises.
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Failed to fetch data:', error.message);
}
}
These examples should give you a good starting point on how to handle errors in various scenarios using JavaScript’s try...catch
mechanism.
![](https://i0.wp.com/basescripts.com/wp-content/uploads/2024/04/image-13.png?resize=536%2C200&ssl=1)