try / exceptHow Python handles things going wrong — catching errors gracefully, keeping your program running, and what to do in the good path, the bad path, and always.
When Python encounters an error at runtime — a file that doesn't exist, a number divided by zero, a network request that times out — it raises an exception. If nothing catches that exception, the program stops immediately and prints a traceback.
Without protection, this code crashes on the second call:
A try block can have up to four parts. Only
| Clause | When it runs | Typical use |
|---|---|---|
| try: | Always — it's the code you're protecting | The risky operation |
| except: | Only when an exception is raised in try | Handle the error, set a default, log it |
| else: | Only when NO exception was raised | Code that should only run on success |
| finally: | Always, no matter what | Cleanup: close files, release locks, disconnect |
You can catch a specific exception type by naming it after
| Exception | When it's raised |
|---|---|
| ValueError | Right type, wrong value — |
| TypeError | Wrong type entirely — |
| KeyError | Dict key doesn't exist — |
| IndexError | List index out of range — |
| AttributeError | Object doesn't have that attribute — |
| FileNotFoundError | File doesn't exist — |
| ZeroDivisionError | Dividing by zero — |
| Exception | The base class — catches any non-system exception |
You can stack multiple
You can raise exceptions yourself with the
For larger applications you can define your own exception classes
by subclassing
At startup, J4H tries to create the AI summarizer.
If the API key isn't set, it raises
When Twilio sends a webhook, the pain level comes in as a string.
Wrapping
Every FHIR server call in
The Admin health dashboard runs 7 service checks concurrently. Each check has its own try/except so one failing service doesn't prevent the others from reporting their status.
Exceptions are not failures — they're expected events.
Networks go down. Users type the wrong thing. Files get deleted.
Writing
The goal is not to hide errors but to handle them at the right level: catch specifically, degrade gracefully, and always clean up after yourself.