The try...catch
statement allows you to handle exceptions (runtime errors) gracefully, preventing them from crashing your entire program. Here’s how it works:
try {
// Code that might throw an exception
// ...
} catch (error) {
// Code to handle the exception
// ...
} finally {
// Optional: Code that runs regardless of whether an exception occurred or not
// ...
}
function divide(a, b) {
try {
if (b === 0) {
throw new Error("Cannot divide by zero");
}
return a / b;
} catch (error) {
console.error("Error:", error.message);
// You can handle the error or rethrow it if needed
// throw error;
} finally {
console.log("This code always runs, regardless of an exception");
}
}
console.log(divide(10, 2)); // Output: 5
console.log(divide(10, 0)); // Output: Error: Cannot divide by zero
// Output: This code always runs, regardless of an exception
Handling Expected Errors:
try...catch
to handle errors that you anticipate might occur in your code.Cleanup with Finally:
finally
block is optional but useful for cleanup tasks that need to run regardless of whether an exception occurred.Rethrowing Exceptions:
JavaScript has several built-in error types, including Error
, SyntaxError
, ReferenceError
, TypeError
, etc.
try {
// Code that might throw an exception
throw new TypeError("This is a custom type error");
} catch (error) {
console.error("Error:", error.message);
} finally {
console.log("Cleanup code");
}
try...catch
is also used with asynchronous code when using async/await
:
async function fetchData() {
try {
const response = await fetch("https://api.example.com/data");
const data = await response.json();
return data;
} catch (error) {
console.error("Error fetching data:", error.message);
throw error; // Rethrow if needed
}
}
// Usage:
fetchData().then(data => console.log("Data:", data)).catch(err => console.error("Fetch error:", err));
try...catch
is a crucial tool for managing errors in JavaScript, allowing you to gracefully handle exceptions and ensure your program continues running smoothly. Use it to handle expected errors, clean up resources, and maintain a robust application.
Splitting a string into an array of substrings is a common operation in C# programming,…
Starting the Docker daemon is the first step towards managing Docker containers and images on…
Serializing an object to JSON (JavaScript Object Notation) format is a common task in C#…
When running Docker containers, you may encounter scenarios where containers need to access resources outside…
Inserting elements into an array dynamically is a common operation in C# programming, especially when…
Utilizing GPUs (Graphics Processing Units) can significantly accelerate certain computational tasks, particularly those involving parallel…