✅ What is try...catch?
try...catch is a built-in error handling mechanism in JavaScript. It allows you to write code that may throw an error, and then catch and handle that error without crashing the application.
<div class="infographic-tryconcept">
<style>
.infographic-tryconcept {
--ink: #1a1a1a;
--ink-soft: #5c5c5c;
--paper: #ffffff;
--paper-alt: #f0ece4;
--line: #ddd6c9;
--accent: #2563eb;
--accent-soft:#e3ebfd;
--ok: #1a7f4e;
--ok-soft: #e3f5ec;
--bad: #b42318;
--bad-soft: #fbe9e7;
--display-font: 'Fraunces', Georgia, serif;
--body-font: 'Inter', -apple-system, sans-serif;
--mono-font: 'IBM Plex Mono', 'Courier New', monospace;
margin: 0 auto;
box-sizing: border-box;
font-family: var(--body-font);
color: var(--ink);
background: var(--paper);
}
.infographic-tryconcept[data-theme="dark"] {
--ink: #e8e6e1;
--ink-soft: #9a968c;
--paper: #121212;
--paper-alt: #1e1e26;
--line: #2c313d;
--accent: #5b8def;
--accent-soft:#202942;
--ok: #5cd6a0;
--ok-soft: #16342a;
--bad: #e57373;
--bad-soft: #3a2222;
}
.infographic-tryconcept * { box-sizing: border-box; }
.infographic-tryconcept .ig-inner { padding: 1.75rem clamp(1.25rem, 5vw, 3rem) 2rem; }
.infographic-tryconcept .ig-title {
font-family: var(--display-font); font-size: clamp(1.4rem, 4.5vw, 1.9rem);
font-weight: 600; text-align: center; margin: 0 0 1.5rem;
}
.infographic-tryconcept .toggle-row { display: flex; align-items: center; justify-content: center; gap: 0.75rem; margin-bottom: 1.5rem; }
.infographic-tryconcept .toggle-label { font-family: var(--mono-font); font-size: 0.82rem; font-weight: 700; color: var(--ink-soft); transition: color 0.2s; cursor: pointer; }
.infographic-tryconcept .toggle-label.active.ok-side { color: var(--ok); }
.infographic-tryconcept .toggle-label.active.bad-side { color: var(--bad); }
.infographic-tryconcept .switch {
position: relative; width: 3.4rem; height: 1.8rem; border-radius: 999px; cursor: pointer;
background: var(--ok); transition: background 0.3s;
}
.infographic-tryconcept .switch.is-on { background: var(--bad); }
.infographic-tryconcept .switch .knob {
position: absolute; top: 0.18rem; left: 0.18rem; width: 1.44rem; height: 1.44rem; border-radius: 50%;
background: #fff; transition: transform 0.3s cubic-bezier(.4,1.4,.6,1); box-shadow: 0 1px 3px rgba(0,0,0,0.3);
}
.infographic-tryconcept .switch.is-on .knob { transform: translateX(1.6rem); }
/* Scene */
.infographic-tryconcept .scene-wrap { display: flex; justify-content: center; }
.infographic-tryconcept .scene {
position: relative; width: 100%; max-width: 480px; height: 190px;
background: var(--paper-alt); border: 1px solid var(--line); border-radius: 10px; overflow: hidden;
}
.infographic-tryconcept .pole { position: absolute; top: 20px; width: 6px; height: 70px; background: var(--ink-soft); border-radius: 3px; opacity: 0.5; }
.infographic-tryconcept .pole.left { left: 26px; }
.infographic-tryconcept .pole.right { right: 26px; }
.infographic-tryconcept .wire { position: absolute; top: 42px; left: 30px; right: 30px; height: 2px; background: var(--ink-soft); opacity: 0.5; }
.infographic-tryconcept .net {
position: absolute; left: 50%; top: 118px; width: 150px; height: 46px; transform: translateX(-50%);
border: 2px dashed var(--line); border-radius: 50% 50% 40% 40%; opacity: 0.5;
transition: border-color 0.3s ease, opacity 0.3s ease, transform 0.3s ease;
}
.infographic-tryconcept .net.is-active { border-color: var(--bad); opacity: 1; border-style: solid; transform: translateX(-50%) scaleY(1.15); }
.infographic-tryconcept .net-label {
position: absolute; left: 50%; top: 168px; transform: translateX(-50%);
font-family: var(--mono-font); font-size: 0.62rem; color: var(--ink-soft);
}
.infographic-tryconcept .walker {
position: absolute; left: 30px; top: 42px; transform: translate(-50%, -85%);
font-size: 1.6rem; transition: left 1.1s ease, top 0.5s ease; z-index: 3;
}
.infographic-tryconcept .broom {
position: absolute; left: 30px; top: 20px; transform: translate(-50%, 0);
font-size: 1.4rem; opacity: 0; transition: left 1.1s ease, opacity 0.2s ease; z-index: 2;
}
.infographic-tryconcept .broom.is-visible { opacity: 1; }
.infographic-tryconcept .stage-tag {
position: absolute; top: 8px; left: 12px; font-family: var(--mono-font); font-size: 0.65rem; font-weight: 700;
color: var(--ink-soft); background: var(--paper); padding: 0.1rem 0.4rem; border-radius: 4px;
}
.infographic-tryconcept .controls { display: flex; justify-content: center; gap: 0.6rem; margin: 1.5rem 0 1rem; }
.infographic-tryconcept .ctrl-btn {
font: inherit; font-size: 0.85rem; font-weight: 700; border: none; background: var(--accent);
color: #fff; padding: 0.55rem 1.2rem; border-radius: 999px; cursor: pointer; font-family: var(--mono-font);
}
.infographic-tryconcept .ctrl-btn.ghost { background: transparent; border: 1px solid var(--line); color: var(--ink-soft); }
.infographic-tryconcept .ctrl-btn:hover { opacity: 0.9; }
.infographic-tryconcept .caption {
text-align: center; font-size: 0.85rem; color: var(--ink-soft); min-height: 1.3em;
}
.infographic-tryconcept .caption strong { color: var(--ink); }
@media (prefers-reduced-motion: reduce) {
.infographic-tryconcept *, .infographic-tryconcept *::before, .infographic-tryconcept *::after {
animation-duration: 0.001ms !important; transition-duration: 0.001ms !important;
}
}
</style>
<div class="ig-inner">
<h2 class="ig-title">try, catch, finally</h2>
<div class="toggle-row">
<span class="toggle-label ok-side active" id="labelOk">smooth crossing</span>
<div class="switch" id="switch"><div class="knob"></div></div>
<span class="toggle-label bad-side" id="labelBad">they trip</span>
</div>
<div class="scene-wrap">
<div class="scene" id="scene">
<span class="stage-tag" id="stageTag">try</span>
<div class="pole left"></div>
<div class="pole right"></div>
<div class="wire"></div>
<div class="net" id="net"></div>
<div class="net-label">catch — only used if they fall</div>
<div class="broom" id="broom">🧹</div>
<div class="walker" id="walker">🚶</div>
</div>
</div>
<div class="controls">
<button class="ctrl-btn" id="goBtn">▶ Go</button>
<button class="ctrl-btn ghost" id="restartBtn">⟲ Restart</button>
</div>
<p class="caption" id="caption">flip the switch, then press Go</p>
</div>
</div>
<script>
(function () {
const wrapper = document.currentScript.closest('.infographic-tryconcept')
|| document.querySelector('.infographic-tryconcept');
const bodyAttr = document.body.getAttribute('data-darkmode');
let dark;
if (bodyAttr === 'true') {
dark = true;
} else if (bodyAttr === 'false') {
dark = false;
} else {
const match = document.cookie.match(/(?:^|;\s*)darkMode=([^;]+)/);
dark = match ? match[1] === 'true' : false;
}
if (dark) wrapper.setAttribute('data-theme', 'dark');
const switchEl = wrapper.querySelector('#switch');
const labelOk = wrapper.querySelector('#labelOk');
const labelBad = wrapper.querySelector('#labelBad');
const goBtn = wrapper.querySelector('#goBtn');
const restartBtn = wrapper.querySelector('#restartBtn');
const caption = wrapper.querySelector('#caption');
const scene = wrapper.querySelector('#scene');
const stageTag = wrapper.querySelector('#stageTag');
const walker = wrapper.querySelector('#walker');
const net = wrapper.querySelector('#net');
const broom = wrapper.querySelector('#broom');
const LEFT_X = 30, RIGHT_X = 450, TRIP_X = 260, WIRE_Y = 42, NET_Y = 138;
let trips = false;
let running = false;
let timers = [];
function clearTimers() { timers.forEach(t => clearTimeout(t)); timers = []; }
function resetVisual() {
clearTimers();
walker.style.transition = 'none';
walker.style.left = LEFT_X + 'px';
walker.style.top = WIRE_Y + 'px';
walker.textContent = '🚶';
broom.style.transition = 'none';
broom.style.left = LEFT_X + 'px';
broom.classList.remove('is-visible');
net.classList.remove('is-active');
stageTag.textContent = 'try';
void walker.offsetWidth; // force reflow so transitions re-apply next time
walker.style.transition = '';
broom.style.transition = '';
}
function run() {
if (running) return;
running = true;
resetVisual();
goBtn.disabled = true;
stageTag.textContent = 'try';
caption.innerHTML = `<strong>they step onto the wire</strong> — the attempt begins`;
if (trips) {
// walk to trip point, then fall into the net
walker.style.left = TRIP_X + 'px';
timers.push(setTimeout(() => {
walker.textContent = '😵';
walker.style.top = NET_Y + 'px';
stageTag.textContent = 'catch';
net.classList.add('is-active');
caption.innerHTML = `<strong>they slip!</strong> the net catches them — disaster handled`;
}, 700));
timers.push(setTimeout(() => {
stageTag.textContent = 'finally';
broom.classList.add('is-visible');
broom.style.left = RIGHT_X + 'px';
caption.innerHTML = `<strong>cleanup happens either way</strong> — the wire gets packed up`;
}, 1600));
} else {
// walk all the way across
walker.style.left = RIGHT_X + 'px';
timers.push(setTimeout(() => {
walker.textContent = '🎉';
stageTag.textContent = 'try';
caption.innerHTML = `<strong>they make it across safely</strong> — the net was never needed`;
}, 1100));
timers.push(setTimeout(() => {
stageTag.textContent = 'finally';
broom.classList.add('is-visible');
broom.style.left = RIGHT_X + 'px';
caption.innerHTML = `<strong>cleanup happens either way</strong> — the wire gets packed up`;
}, 1500));
}
timers.push(setTimeout(() => { running = false; goBtn.disabled = false; }, trips ? 2100 : 2000));
}
function restart() {
running = false;
goBtn.disabled = false;
resetVisual();
caption.textContent = 'flip the switch, then press Go';
}
function setTrips(val) {
trips = val;
switchEl.classList.toggle('is-on', trips);
labelBad.classList.toggle('active', trips);
labelOk.classList.toggle('active', !trips);
restart();
}
switchEl.addEventListener('click', () => setTrips(!trips));
labelOk.addEventListener('click', () => setTrips(false));
labelBad.addEventListener('click', () => setTrips(true));
goBtn.addEventListener('click', run);
restartBtn.addEventListener('click', restart);
resetVisual();
})();
</script>.demo {
font-family: system-ui, sans-serif;
padding: 16px;
}
.demo h1 {
color: #2563eb;
margin: 0 0 8px;
}
.demo p {
color: #4b5563;
margin: 0;
}document.querySelector('.demo h1')?.addEventListener('click', () => {
alert('Hello from live preview!');
});🧱 Syntax
try {
// Code that might throw an error
} catch (error) {
// Code to handle the error
}⚙️ How it Works
The code inside the
tryblock is executed.If there’s an error, the rest of the
tryblock is skipped.The
catchblock is executed with the error passed as a parameter.
📌 Example 1: Basic Error Catching
// app.js (Running in Node.js)
try {
let a = b + 1; // ❌ b is not defined
} catch (error) {
console.log("An error occurred:", error.message);
}An error occurred: b is not defined📌 Example 2: JSON Parsing
// app.js (Node.js)
try {
let user = JSON.parse('{"name": "Codeveda"'); // Missing closing brace
} catch (e) {
console.error("Parsing error:", e.message);
}Parsing error: Unexpected end of JSON input🧪 Example 3: Catching TypeError
// app.js (Node.js)
try {
null.f(); // ❌ Cannot call function on null
} catch (err) {
console.error("Error Type:", err.name); // TypeError
console.error("Message:", err.message);
}Error Type: TypeError
Message: Cannot read properties of null (reading 'f')✅ What is finally?
The finally block always runs — whether an error was thrown or not. It is useful for cleanup logic like closing files, releasing resources, or ending a loading spinner.
🧱 Syntax with finally
try {
// Code that might throw
} catch (error) {
// Handle the error
} finally {
// Code that always runs
}📌 Example 4: try...catch...finally
try {
console.log("Start");
let result = 10 / 0;
console.log("Result:", result);
} catch (error) {
console.error("Error caught:", error.message);
} finally {
console.log("This always runs.");
}Start
Result: Infinity
This always runs.Even though no error is thrown here, finally still runs.
📌 Example 5: Error with finally
try {
throw new Error("Manual error");
} catch (e) {
console.log("Caught:", e.message);
} finally {
console.log("Cleaning up...");
}Caught: Manual error
Cleaning up...✅ When to Use
Scenario | Use | Use |
|---|---|---|
Invalid JSON parsing | ✅ | ❌ |
External API call | ✅ | ✅ (cleanup/loading spinner) |
File I/O or DB operations | ✅ | ✅ |
User input validation | ✅ | ❌ (often better to use conditional checks) |
❗Important Notes
Only runtime errors are caught. Syntax errors won't be caught because the script won't run at all.
Works only in synchronous code, unless you're using
async/awaitinsidetry.
📌 Example 6: Async + try...catch
async function fetchData() {
try {
const res = await fetch('<https://api.example.com/data>');
const data = await res.json();
console.log(data);
} catch (error) {
console.error("Fetch failed:", error.message);
} finally {
console.log("Fetch attempt completed.");
}
}If Api fails to fetch data
Fetch failed: Failed to fetch
Fetch attempt completed.📋 Summary
Block | Purpose |
|---|---|
| Run code that might throw an error |
| Handle any error thrown in the |
| Code that always runs (cleanup/logs/etc.) |