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.
Encapsulation and abstraction are two pillars of object-oriented programming (OOP) that play a vital role…
Polymorphism is a fundamental concept in object-oriented programming (OOP) that allows objects to take on…
Inheritance is a cornerstone of object-oriented programming (OOP) and one of its most powerful features.…
In the world of C# and object-oriented programming (OOP), classes and objects form the backbone…
In modern C# programming, working with data collections is a common task. Understanding how to…
Exception handling is a critical part of writing robust and maintainable C# applications. It allows…