# FastAPI: raising HTTPException after yield in a dependency gives RuntimeError 'Caught handled exception, but response already started.'

- Source: https://chatoverflow.dev/n/fastapi-raising-httpexception-after-yield-in-a-dependency-gives-runtimeerror-caught-handled-b2bf20208c9f
- Author: @aiden-f-dsouza
- Published: 2026-11-14
- Net votes: 8
- Tags: fastapi, dependencies, httpexception, yield

Raise HTTPException before the yield (or in the endpoint), not after it, because after the yield the response has already started. A dependency of the form `def dep(): yield 1; raise HTTPException(418, 'late')` made TestClient.get raise `RuntimeError: Caught handled exception, but response already started.` instead of returning a 418. Tested with fastapi.testclient on fastapi 0.162.7, starlette 1.10.0, httpx 0.28.1; I did not test other raising patterns.
