Error handling is the part of Python a Java developer learns fastest. You already know the model: something goes wrong, an exception is thrown, it travels up the call stack until someone catches it, and finally cleans up. Python works exactly the same way.
What changes is the vocabulary, the list of built-in errors, and one big thing that’s missing: checked exceptions. Nothing in Python forces you to catch or declare anything. That makes code shorter and puts the responsibility on you.
This is part 7 of Python for Java Developers. Part 6 covered classes, dataclasses and Pydantic; you’ll write your own exception class below.
try, except, finally
try {
result = callModel(prompt);
} catch (TimeoutException e) {
log.warn("Timed out", e);
} finally {
close();
}try:
result = call_model(prompt)
except TimeoutError as e:
print("Timed out:", e)
finally:
close()catch (Type e) becomes except Type as e:. Everything else is the same idea.
Python adds one optional block, else, which runs only when the try block raised nothing. It keeps the “success” code out of the try, so you don’t accidentally catch errors from it:
try:
data = json.loads(text)
except json.JSONDecodeError:
data = {}
else:
print("Parsed", len(data), "fields") # only if loads() succeeded
Catching several types
Java’s multi-catch catch (A | B e) is a tuple in Python:
try:
value = config["timeout"]
seconds = int(value)
except (KeyError, ValueError) as e:
seconds = 30
You can also stack several except blocks, most specific first, just like Java’s catch blocks.
raise: Python’s throw
def set_temperature(value):
if not 0 <= value <= 1:
raise ValueError(f"temperature must be between 0 and 1, got {value}")
To rethrow the current exception inside an except block, write raise on its own. To wrap one exception in another, Java’s new ServiceException("...", cause), use raise ... from:
try:
reply = client.messages.create(...)
except anthropic.APIError as e:
raise SummaryFailed("could not summarize document") from e
The traceback then shows both errors, linked by “The above exception was the direct cause of the following exception”, just like Java’s “Caused by”.
Your own exceptions
Extend Exception. The smallest useful custom exception is two lines:
class SummaryFailed(Exception):
pass
pass means “nothing here”; the class is complete. Add fields when callers need them:
class RateLimited(Exception):
def __init__(self, retry_after):
super().__init__(f"rate limited, retry after {retry_after}s")
self.retry_after = retry_after
Extend Exception, never BaseException. BaseException also covers things like Ctrl+C (KeyboardInterrupt) and SystemExit, which you almost never want to catch, much like Java’s Error.
Built-in errors you’ll meet, and their Java cousins
| Python | Raised when | Java cousin |
|---|---|---|
AttributeError |
Calling a method or field that isn’t there, often on None |
NullPointerException |
KeyError |
d[key] on a missing key |
(Java returns null instead) |
IndexError |
List index out of range | IndexOutOfBoundsException |
TypeError |
Wrong type, or wrong number of arguments | ClassCastException, compile errors |
ValueError |
Right type, bad value: int("abc") |
IllegalArgumentException, NumberFormatException |
FileNotFoundError |
Opening a missing file | FileNotFoundException |
ImportError / ModuleNotFoundError |
A package isn’t installed | ClassNotFoundException |
NotImplementedError |
A method a subclass should override | UnsupportedOperationException |
TimeoutError |
An operation timed out | TimeoutException |
The most famous one deserves its own line: AttributeError: 'NoneType' object has no attribute 'strip' is Python’s NullPointerException. Something returned None where you expected a value.
Reading a traceback: bottom up
A Python error prints a traceback. Read it from the bottom:
Traceback (most recent call last):
File "app.py", line 12, in <module>
main()
File "app.py", line 8, in main
print(summarize(doc))
File "app.py", line 3, in summarize
return doc.strip()[:100]
AttributeError: 'NoneType' object has no attribute 'strip'
The last line is the error. The lines above it are the call stack, newest call last. A Java stack trace is the other way round, newest call first, so your eyes will look in the wrong place for a week. Here, summarize got None as doc, and line 3 is where it failed.
Ask forgiveness, not permission
Java code often checks first, then acts. Python style usually tries first and handles the failure. The Python community calls it EAFP: easier to ask forgiveness than permission.
if (counts.containsKey(word)) {
counts.put(word, counts.get(word) + 1);
} else {
counts.put(word, 1);
}try:
counts[word] += 1
except KeyError:
counts[word] = 1
# or, simplest of all:
counts[word] = counts.get(word, 0) + 1Both styles work in Python. Prefer try/except when the failure is rare, and a simple check (or .get()) when it’s common.
A retry loop, the way AI code does it
Calls to LLM APIs fail now and then: rate limits, timeouts, overloaded servers. SDKs raise their own exception classes, and a small retry loop handles them:
import time
import anthropic
client = anthropic.Anthropic()
for attempt in range(3):
try:
reply = client.messages.create(model=MODEL, max_tokens=500, messages=messages)
break # success: leave the loop
except anthropic.RateLimitError:
time.sleep(2 ** attempt) # wait 1, 2, 4 seconds
else:
raise RuntimeError("still rate limited after 3 attempts")
The else on the for loop runs only if the loop never hit break, so the error is raised only when every attempt failed. (Many SDKs also retry automatically; check yours before adding a loop.) For real projects, the tenacity library does the same with a decorator, which you’ll meet in the decorators part of this series.
Logging an exception
Inside an except block, logging.exception writes the message and the full traceback, like log.error("...", e) in SLF4J:
import logging
try:
process(doc)
except Exception:
logging.exception("failed to process %s", doc.id)
raise
Traps for Java developers
- Bare
except:orexcept Exception: pass. It catches everything and hides real bugs. AI assistants write it often. Catch the errors you can actually handle. - Assuming someone will force you to handle errors. With no checked exceptions, nothing reminds you that a call can fail. Read the docs of the library you call.
- Reading tracebacks top down. The error and the line that failed are at the bottom.
- Using exceptions for normal flow everywhere. EAFP is fine, but a
.get()with a default is clearer for missing dict keys.
Key takeaways
try/except Type as e/else/finally.catchisexcept,throwisraise.- Catch several types with a tuple:
except (KeyError, ValueError):. - Rethrow with a bare
raise; wrap withraise New(...) from e. - Custom exceptions extend
Exception, and two lines are enough. AttributeError: 'NoneType'...is Python’s NullPointerException.- There are no checked exceptions, and tracebacks are read from the bottom.
Frequently asked questions
Does Python have checked exceptions?
No. Any function can raise any exception, and there’s no throws clause. You decide what to catch, usually based on the library’s documentation.
What is the difference between except and catch?
Only the word. Python’s except ValueError as e: does what Java’s catch (IllegalArgumentException e) does: it handles one type of exception raised in the try block.
How do I create a custom exception in Python?
Write a class that extends Exception: class SummaryFailed(Exception): pass. Raise it with raise SummaryFailed("message"), and add an __init__ if it needs extra fields.
What is the Python equivalent of NullPointerException?
AttributeError: 'NoneType' object has no attribute .... It means you used a method or field on None. A TypeError such as 'NoneType' object is not subscriptable means the same thing for [] access.
What does raise from do in Python?
raise NewError(...) from original raises a new exception and records the original as its cause. The traceback shows both, like Java’s “Caused by” chain.
That completes the “same idea, new syntax” half of the series. Next come the Python ideas Java doesn’t have, starting with Python list comprehensions vs Java streams.
Comments