Try/Catch
ELI5 — The Vibe Check
Try/catch is your safety net. You put risky code in the 'try' box, and if it blows up, the 'catch' box catches the explosion and handles it gracefully instead of crashing. It is like trying to open a jar — try it, and if you cannot, catch the situation and ask for help.
Real Talk
Try/catch is a control flow structure for exception handling. Code in the try block executes normally; if an exception is thrown, execution jumps immediately to the catch block, which receives the error object. An optional finally block always executes regardless of success or failure, commonly used for cleanup (closing files, releasing resources).
Show Me The Code
async function fetchUser(id) {
try {
const response = await fetch(`/api/users/${id}`);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return await response.json();
} catch (error) {
console.error("Failed to fetch user:", error.message);
return null; // graceful fallback
} finally {
console.log("Request completed"); // always runs
}
}
When You'll Hear This
"Wrap the API call in a try/catch." / "The try/catch swallowed the error — log it!"
Related Terms
Async/Await
Async/await is syntactic sugar that makes Promises look like normal, readable code. Instead of chaining .then().then().
Error
An error is when your program says 'I cannot do that' and either stops or complains loudly. It is the computer's way of telling you something went wrong.
Error Handling
Error handling is the art of planning for things to go wrong and dealing with them gracefully instead of letting everything catch fire.
Exception
An exception is a special kind of error that 'throws' itself up through your code like a hot potato, looking for someone to catch it.
Logging
Logging is writing a diary for your program.