✅ What is Exception Handling?
It’s the process of catching and handling runtime errors in a graceful manner to avoid crashing the program.
🔧 Syntax:
try:
# risky code
except SomeError:
# handle error💡 Example:
try:
number = int(input("Enter a number: "))
print("You entered:", number)
except ValueError:
print("Oops! Please enter a valid number.")✅ Helps to gracefully deal with situations that may crash your program.
Output -1 (Valid Input)
Enter a number: 42
You entered: 42Output - 2(Invalid Input)
Enter a number: hello
Oops! Please enter a valid number.✅The else block
🏠 Real-life Analogy:
You try to turn on a fan (try). If the power is off (except), you handle it.
If everything is fine, you relax and enjoy (
else).
✅ Python Example:
try:
result = 10 / 2
except ZeroDivisionError:
print("You can’t divide by zero.")
else:
print("Everything went fine! Result is:", result)Everything went fine! Result is: 5.0✅ Why use else?
To run something only if no error occurred.
It keeps your code neat — you don’t mix “success” code inside try or except.
🔹 finally Clause — Explained Simply
💬 What does it do?
The finally block runs no matter what — even if there’s an error or not.
🧼 Real-life Analogy:
You’re cooking (try), and something might go wrong (like spilling).
Whether it goes well or not, you still clean the kitchen (
finally).
✅ Python Example:
try:
f = open("data.txt", "r") # Trying to open a file
except FileNotFoundError:
print("File not found.")
finally:
print("Closing everything... Done.")# 🖨️ Output if file does not exist:
File not found.
Closing everything... Done.# 🖨️ Output if file exists:
Closing everything... Done.🔍 Why Use Try-Except?
Prevents your app from crashing.
Gives clear feedback to users.
Maintains smooth user experience.
✅ Why use finally?
To clean up (like closing files, releasing memory, disconnecting a server)
It ensures that certain code always runs, even if something goes wrong
<div class="infographic-pytryexcept">
<style>
.infographic-pytryexcept {
--ink: #1a1a1a;
--ink-soft: #5c5c5c;
--paper: #ffffff;
--paper-alt: #f0ece4;
--accent: #2563eb; --accent-soft: #e3ebfd;
--line: #ddd6c9;
--c-zde: #c0392b; --c-zde-soft: #fbe9e7;
--c-te: #b45309; --c-te-soft: #fdf0dc;
--c-else: #1f9d55; --c-else-soft: #e3f5ec;
--c-fin: #9333ea; --c-fin-soft: #f3e8fd;
--mono-font: 'IBM Plex Mono', 'SFMono-Regular', Menlo, monospace;
--display-font: 'Fraunces', Georgia, serif;
--body-font: 'Inter', system-ui, sans-serif;
box-sizing: border-box;
max-width: 700px;
margin: 0 auto;
font-family: var(--body-font);
color: var(--ink);
background: var(--paper);
}
.infographic-pytryexcept[data-theme="dark"] {
--ink: #e8e6e1;
--ink-soft: #9a968c;
--paper: #121212;
--paper-alt: #1e1e26;
--accent: #5b8def; --accent-soft: #202942;
--line: #2c313d;
--c-zde: #e57373; --c-zde-soft: #3a2222;
--c-te: #e0a458; --c-te-soft: #3a2c14;
--c-else: #6fdc8c; --c-else-soft: #16342a;
--c-fin: #c58af2; --c-fin-soft: #2e2140;
}
.infographic-pytryexcept *, .infographic-pytryexcept *::before, .infographic-pytryexcept *::after { box-sizing: border-box; }
.infographic-pytryexcept .te-wrap { padding: 0 clamp(1rem, 4vw, 2rem) 1.5rem; }
.infographic-pytryexcept h1 {
font-family: var(--display-font); font-weight: 600;
font-size: clamp(1.45rem, 5vw, 1.95rem); text-align: center; margin: 1.5rem 0 0.25rem; letter-spacing: -0.01em;
}
.infographic-pytryexcept .te-sub { text-align: center; color: var(--ink-soft); font-size: 0.85rem; margin: 0 0 1.3rem; }
.infographic-pytryexcept .code-block {
font-family: var(--mono-font); font-size: 0.8rem; line-height: 1.75; white-space: pre;
background: var(--paper-alt); border: 1px solid var(--line); border-radius: 8px;
padding: 0.85rem 1rem; margin-bottom: 1.1rem;
}
.infographic-pytryexcept .code-block .kw { color: var(--accent); font-weight: 700; }
.infographic-pytryexcept .blk { border-radius: 5px; padding: 0.05rem 0.15rem; transition: background 0.35s, box-shadow 0.35s; }
.infographic-pytryexcept .blk.try-b.is-on { background: var(--accent-soft); box-shadow: 0 0 0 1.5px var(--accent); }
.infographic-pytryexcept .blk.zde-b.is-on { background: var(--c-zde-soft); box-shadow: 0 0 0 1.5px var(--c-zde); }
.infographic-pytryexcept .blk.te-b.is-on { background: var(--c-te-soft); box-shadow: 0 0 0 1.5px var(--c-te); }
.infographic-pytryexcept .blk.else-b.is-on { background: var(--c-else-soft); box-shadow: 0 0 0 1.5px var(--c-else); }
.infographic-pytryexcept .blk.fin-b.is-on { background: var(--c-fin-soft); box-shadow: 0 0 0 1.5px var(--c-fin); }
.infographic-pytryexcept .row { display: flex; justify-content: center; gap: 0.5rem; margin-bottom: 0.9rem; flex-wrap: wrap; align-items: center; }
.infographic-pytryexcept .row span { font-family: var(--mono-font); font-size: 0.82rem; color: var(--ink-soft); }
.infographic-pytryexcept .row input {
font-family: var(--mono-font); font-size: 0.85rem; padding: 0.4rem 0.6rem;
border: 1.5px solid var(--line); border-radius: 5px; background: var(--paper-alt); color: var(--ink); width: 90px;
text-align: center;
}
.infographic-pytryexcept .row input:focus { outline: none; border-color: var(--accent); }
.infographic-pytryexcept .preset-row { display: flex; justify-content: center; gap: 0.4rem; margin-bottom: 0.9rem; flex-wrap: wrap; }
.infographic-pytryexcept .preset-btn {
font: inherit; font-family: var(--mono-font); font-size: 0.74rem; font-weight: 700;
background: var(--paper-alt); border: 1.5px dashed var(--line); color: var(--ink-soft);
padding: 0.3rem 0.6rem; cursor: pointer; border-radius: 999px;
}
.infographic-pytryexcept .run-row { display: flex; justify-content: center; margin-bottom: 1rem; }
.infographic-pytryexcept .run-btn {
font: inherit; font-family: var(--mono-font); font-size: 0.85rem; font-weight: 700;
background: var(--accent); color: #fff; border: none; border-radius: 999px;
padding: 0.55rem 1.2rem; cursor: pointer;
}
.infographic-pytryexcept .run-btn:disabled { opacity: 0.5; cursor: default; }
.infographic-pytryexcept .device {
--ed-bg: #1e1e1e; --ed-bar: #2d2d2d; --ed-text: #d4d4d4; --ed-soft: #8a8a8a; --ed-ok: #6fdc8c;
background: var(--ed-bg); border: 1px solid var(--line); border-radius: 8px; overflow: hidden;
}
.infographic-pytryexcept .device-bar {
display: flex; align-items: center; gap: 0.4rem;
background: var(--ed-bar); padding: 0.5rem 0.7rem; border-bottom: 1px solid #3a3a3a;
font-size: 0.72rem; color: var(--ed-soft); font-weight: 600;
}
.infographic-pytryexcept .device-bar .dot { width: 9px; height: 9px; border-radius: 50%; background: #5a5a5a; }
.infographic-pytryexcept .device-bar .dot:nth-child(1) { background: #ff5f56; }
.infographic-pytryexcept .device-body { padding: 0.75rem 0.9rem; font-family: var(--mono-font); font-size: 0.8rem; color: var(--ed-text); min-height: 80px; }
.infographic-pytryexcept .log-line { line-height: 1.7; opacity: 0; animation: te-fadein 0.25s ease forwards; }
@keyframes te-fadein { from { opacity: 0; } to { opacity: 1; } }
.infographic-pytryexcept .log-empty { color: var(--ed-soft); }
@media (prefers-reduced-motion: reduce) {
.infographic-pytryexcept *, .infographic-pytryexcept *::before, .infographic-pytryexcept *::after {
animation-duration: 0.001ms !important; transition-duration: 0.001ms !important;
}
}
</style>
<div class="te-wrap">
<h1>try / except / else / finally</h1>
<p class="te-sub">Pick a and b. Watch exactly which block actually runs.</p>
<div class="code-block" id="codeBlock"><span class="kw">try</span>:
<span class="blk try-b" id="bTry">result = a / b</span>
<span class="kw">except</span> ZeroDivisionError:
<span class="blk zde-b" id="bZde">print("Cannot divide by zero!")</span>
<span class="kw">except</span> TypeError:
<span class="blk te-b" id="bTe">print("Invalid types!")</span>
<span class="kw">else</span>:
<span class="blk else-b" id="bElse">print(f"Result: {result}")</span>
<span class="kw">finally</span>:
<span class="blk fin-b" id="bFin">print("Done attempting division.")</span></div>
<div class="row">
<span>a =</span><input id="aInput" type="text" value="10" />
<span>b =</span><input id="bInput" type="text" value="2" />
</div>
<div class="preset-row">
<button class="preset-btn" data-a="10" data-b="2">a=10, b=2 (works)</button>
<button class="preset-btn" data-a="10" data-b="0">a=10, b=0 (÷ by zero)</button>
<button class="preset-btn" data-a="10" data-b="abc">a=10, b="abc" (bad type)</button>
</div>
<div class="run-row"><button class="run-btn" id="runBtn">Run: safe_divide(a, b)</button></div>
<div class="device">
<div class="device-bar"><span class="dot"></span><span class="dot"></span><span class="dot"></span> Terminal</div>
<div class="device-body" id="teLog"><div class="log-empty">Set a and b, then hit Run.</div></div>
</div>
</div>
<script>
(function () {
var root = document.currentScript.closest('.infographic-pytryexcept')
|| document.querySelector('.infographic-pytryexcept');
var bodyAttr = document.body.getAttribute('data-darkmode');
var dark;
if (bodyAttr === 'true') { dark = true; }
else if (bodyAttr === 'false') { dark = false; }
else {
var match = document.cookie.match(/(?:^|;\s*)darkMode=([^;]+)/);
dark = match ? match[1] === 'true' : false;
}
if (dark) root.setAttribute('data-theme', 'dark');
var aInput = root.querySelector('#aInput');
var bInput = root.querySelector('#bInput');
var runBtn = root.querySelector('#runBtn');
var teLog = root.querySelector('#teLog');
var bTry = root.querySelector('#bTry');
var bZde = root.querySelector('#bZde');
var bTe = root.querySelector('#bTe');
var bElse = root.querySelector('#bElse');
var bFin = root.querySelector('#bFin');
var allBlocks = [bTry, bZde, bTe, bElse, bFin];
var running = false;
root.querySelectorAll('.preset-btn').forEach(function (btn) {
btn.addEventListener('click', function () {
aInput.value = btn.dataset.a;
bInput.value = btn.dataset.b;
});
});
function clearHighlights() {
allBlocks.forEach(function (b) { b.classList.remove('is-on'); });
}
function logLine(text) {
var line = document.createElement('div');
line.className = 'log-line';
line.textContent = text;
teLog.appendChild(line);
teLog.scrollTop = teLog.scrollHeight;
}
runBtn.addEventListener('click', function () {
if (running) return;
running = true;
runBtn.disabled = true;
clearHighlights();
teLog.innerHTML = '';
var aRaw = aInput.value.trim();
var bRaw = bInput.value.trim();
var aNum = parseFloat(aRaw);
var bIsNumeric = /^-?\d+(\.\d+)?$/.test(bRaw);
var bNum = bIsNumeric ? parseFloat(bRaw) : NaN;
var outcome;
if (!bIsNumeric) outcome = 'type';
else if (bNum === 0) outcome = 'zero';
else outcome = 'ok';
var steps = [];
steps.push(function () {
bTry.classList.add('is-on');
logLine('>>> result = ' + aRaw + ' / ' + (bIsNumeric ? bRaw : '"' + bRaw + '"'));
});
if (outcome === 'zero') {
steps.push(function () {
bTry.classList.remove('is-on');
bZde.classList.add('is-on');
logLine('ZeroDivisionError raised — jumping to the matching except block');
logLine('Cannot divide by zero!');
});
} else if (outcome === 'type') {
steps.push(function () {
bTry.classList.remove('is-on');
bTe.classList.add('is-on');
logLine('TypeError raised — jumping to the matching except block');
logLine('Invalid types!');
});
} else {
steps.push(function () {
bTry.classList.remove('is-on');
bElse.classList.add('is-on');
logLine('No exception — else runs, except blocks are skipped entirely');
logLine('Result: ' + (aNum / bNum));
});
}
steps.push(function () {
allBlocks.forEach(function (b) { if (b !== bFin) b.classList.remove('is-on'); });
bFin.classList.add('is-on');
logLine('finally always runs, no matter what happened above');
logLine('Done attempting division.');
});
var i = 0;
function next() {
if (i < steps.length) {
steps[i]();
i++;
setTimeout(next, 750);
} else {
running = false;
runBtn.disabled = false;
}
}
next();
});
})();
</script>
</div>