The Injury Report: Error Handling in JavaScript π₯

Welcome to the Season Finale of JavaScript: The Champions League Series π.
Even the best-laid tactical plans can go wrong. A star player gets injured, the bus breaks down, or the referee makes a terrible call. In JavaScript, these are called Errors. If you don't handle them, your entire "Match" (your app) crashes and burns.
Today, weβre learning how to write the Injury Report: Mastering try, catch, and finally.
1. Why Do We Need Error Handling?
Imagine a striker takes a shot. Normally, it goes into the net. But what if the ball bursts? Or a fan runs onto the pitch? If your code only knows how to handle "Goals," it won't know what to do when something unexpected happens.
Without error handling, a single failed API call or a typo in a variable name will stop your entire script.
2. The Defense Trio: Try, Catch, and Finally
The try Block (The Attempt)
This is where you put the code that might fail. Youβre telling JavaScript: "Try to run this play, but keep a close eye on it."
The catch Block (The Goalkeeper)
If an error occurs inside the try block, JavaScript immediately jumps to the catch block. It "catches" the error object, which contains information about what went wrong.
The finally Block (The Post-Match Analysis)
The finally block runs no matter what. Whether the play was a success or a total disaster, finally always executes. This is perfect for "cleanup" tasks, like closing a database connection or hiding a loading spinner.
try {
console.log("Attempting the winning goal...");
// Simulating an error: calling a function that doesn't exist
performBicycleKick();
} catch (error) {
console.log(`Injury Report: ${error.message}`); // "performBicycleKick is not defined"
} finally {
console.log("The whistle blows. Players head to the locker room.");
}
3. Throwing Your Own Errors: The Referee's Whistle
Sometimes, the code technically "works," but it violates your rules. For example, a player's age cannot be negative. You can use the throw keyword to manually trigger an error and send it to the catch block.
function setPlayerAge(age) {
if (age < 0) {
throw new Error("Age cannot be negative! π©");
}
return `Age set to ${age}`;
}
try {
setPlayerAge(-5);
} catch (e) {
console.log(e.message);
}
4. Real-World Use Case: The API Call
In modern development, try...catch is most commonly used with async/await to handle network issues.
async function fetchSquad() {
try {
const response = await fetch('https://api.football.com/squad');
if (!response.ok) throw new Error("Network response was not ok");
const data = await response.json();
console.log(data);
} catch (err) {
console.error("Failed to load squad. Please check your internet. π‘");
} finally {
hideLoadingSpinner(); // Always hide the spinner!
}
}
π Daily Drill: The Foul Check β½
Head to your console for the final training drill of the season:
The Safe Bet: Write a
try...catchblock that tries to log a variable that exists. Observe that thecatchblock is skipped.The Foul: Try to log a variable that doesn't exist. Capture the error and log its
.nameand.message.The Manual Whistle: Create a function that throws an error if a number passed to it is greater than 10.
The Clean Up: Add a
finallyblock to any of the above that logs "Operation Attempted."
How does it feel knowing your app won't crash even if things go wrong? Let me know in the comments!



