The try...catch block allows you to "try" a block of code and "catch" any errors that occur, so you can handle them gracefully instead of letting the program die.
1. The try block
Put the code that might fail (like a network request) inside here.
2. The catch block
If an error happens in the try block, JavaScript immediately jumps here. The error object contains details about what went wrong.
3. The finally block
(Optional) This runs no matter what, whether there was an error or not. It's great for "cleanup" (like hiding a loading spinner).
The Code Example
async function fetchUserSafe() {
console.log("Starting request...");
try {
// We "try" to fetch data
const response = await fetch("https://api.invalid-url.com/user");
if (!response.ok) {
// Manually 'throw' an error if the server says no
throw new Error("User not found!");
}
const data = await response.json();
console.log(data);
} catch (error) {
// If anything fails above, we end up here
console.error("Caught an error: ", error.message);
alert("Sorry, we couldn't load the user data.");
} finally {
// This always runs
console.log("Attempt finished.");
}
}
fetchUserSafe();