Control flow: decisions and loops · Part 6 of 36
Errors, exceptions and debugging
Basic 13 min
Read error messages, catch exceptions with try/catch and try/except, and find bugs systematically.
What you will learn
- You can read a stack trace and find the line that failed.
- You can catch and raise exceptions in both languages.
- You can debug with prints, assertions and a debugger.
Before this: Loops: repeating work
Errors are messages, not failures
When something goes wrong at run time, both languages create an exception — an object that describes the problem — and stop the normal flow. If nobody handles it, the program ends and prints a stack trace:
Traceback (most recent call last):
File "plan.py", line 7, in <module>
rows = beds / per_row
ZeroDivisionError: division by zero
Read it from the bottom: the type (ZeroDivisionError), the message, then the line where it happened (line 7). The lines above show which function called which. JavaScript prints the same information the other way round: message first, then the call stack.
Common types you will meet: TypeError (wrong kind of value, both languages), ReferenceError / NameError (a name that doesn't exist), RangeError, ValueError, KeyError, IndexError.

Catching exceptions
Sometimes you expect a problem and want to react instead of crashing:
try {
const data = JSON.parse(text);
console.log(data.name);
} catch (err) {
console.log("That was not valid JSON:", err.message);
} finally {
console.log("done"); // runs in every case
}
import json
try:
data = json.loads(text)
print(data["name"])
except json.JSONDecodeError as err:
print("That was not valid JSON:", err)
except KeyError:
print("No name in the data")
finally:
print("done")
Python lets you catch specific types; catch only what you can actually handle. A bare except: or an empty catch {} hides bugs — the program carries on with broken data, which is often worse than a crash. (The OWASP Top 10:2025 even lists "Mishandling of Exceptional Conditions" as a security risk.)
You raise your own exceptions with throw new Error("…") in JavaScript and raise ValueError("…") in Python. Do it when a function receives input it cannot work with.
Debugging, step by step
A bug is a logic error. Finding it is a skill you can practise:
- Reproduce it. Find the smallest input that shows the problem.
- Predict. What should each step do? Write it down.
- Observe. Print intermediate values (
console.log,print) or, better, use a debugger: set a breakpoint, run, and step line by line while watching variables. Browser DevTools have one built in; Python hasbreakpoint(), which openspdb; editors such as VS Code have graphical debuggers for both languages. - Compare prediction and observation. The first place they differ is where the bug lives.
- Fix and check — and keep the failing input as a test (you will learn testing in the intermediate tier).
Assertions make your assumptions explicit: assert len(rows) > 0 in Python or console.assert(rows.length > 0) in JavaScript complain the moment an assumption is broken.
Try it: JavaScript sandbox
Write and run small JavaScript programs; the checker tells you when an exercise is solved.
Turn on JavaScript to use this lab. Worked example:
Exercise 6: JSON.parse throws on bad input. Wrap it in try/catch so that the program prints "invalid" for the given text instead of crashing.
Key points
- An exception describes a run-time problem; unhandled, it stops the program with a stack trace.
- Read stack traces for type, message and line number.
try/catch/finally(JavaScript) andtry/except/finally(Python) handle expected problems; catch specific types.- Never swallow errors silently; raise your own with
throw/raise. - Debug systematically: reproduce, predict, observe (prints, breakpoints), compare, fix, keep a test.
Flashcards
- Question: Where do you start reading a Python traceback?
- Answer: At the bottom: error type and message, then the line that failed.
- Question: Which block runs whether or not an exception happened?
- Answer: finally.
- Question: How do you raise an error in Python and in JavaScript?
- Answer: raise ValueError("…") in Python, throw new Error("…") in JavaScript.
- Question: What does breakpoint() do in Python?
- Answer: It pauses the program and opens the pdb debugger.
Check yourself
Think about your answer, then open it. In the app the quiz is interactive, earns points and brings back what you missed.
A traceback ends with KeyError: 'name'. What happened?
- A dictionary had no key "name"
- A variable called name was not defined
- The file name was wrong
- A number was divided by zero
Show the answer
A dictionary had no key "name"
KeyError is raised when you look up a missing key in a dictionary.
Source: Python docs, Built-in Exceptions
Why is an empty catch block dangerous?
- It hides the error and lets the program continue with broken data
- It makes the program slower
- It is a syntax error
- It prints the error twice
Show the answer
It hides the error and lets the program continue with broken data
Swallowed exceptions hide bugs; the program carries on in an unexpected state.
Source: OWASP Top 10:2025 A10
Put the debugging steps in a sensible order.
Show the answer
Reproduce the bug → Predict what should happen → Observe what actually happens → Fix and keep a test
Reproduce first, then compare prediction with observation; fix and protect against regressions.
Source: MIT OCW 6.100L
In Python you open the debugger at a line by calling ___().
Show the answer
breakpoint
breakpoint() enters pdb by default (since Python 3.7).
Source: Python docs, pdb
Sources
- MDN Web Docs JavaScript Guide, Mozilla, 2025
- The Python Tutorial (3.14), Python Software Foundation, 2025
- Python documentation: pdb — The Python Debugger, Python Software Foundation, 2025
Facts checked on 2026-11-30. Skillgrove lessons are free learning material — no certificate and no accreditation.