If you use a try block in a dependency with yield, you'll receive any exception that was thrown when using the dependency.
For example, if some code at some point in the middle, in another dependency or in a path operation, made a database transaction "rollback" or create any other error, you will receive the exception in your dependency.
So, you can look for that specific exception inside the dependency with except SomeException.
In the same way, you can use finally to make sure the exit steps are executed, no matter if there was an exception or not.
You saw that you can use dependencies with yield and have try blocks that catch exceptions.
It might be tempting to raise an HTTPException or similar in the exit code, after the yield. But it won't work.
The exit code in dependencies with yield is executed after the response is sent, so Exception Handlers will have already run. There's nothing catching exceptions thrown by your dependencies in the exit code (after the yield).
So, if you raise an HTTPException after the yield, the default (or any custom) exception handler that catches HTTPExceptions and returns an HTTP 400 response won't be there to catch that exception anymore.
This is what allows anything set in the dependency (e.g. a DB session) to, for example, be used by background tasks.
Background tasks are run after the response has been sent. So there's no way to raise an HTTPException because there's not even a way to change the response that is already sent.
But if a background task creates a DB error, at least you can rollback or cleanly close the session in the dependency with yield, and maybe log the error or report it to a remote tracking system.
If you have some code that you know could raise an exception, do the most normal/"Pythonic" thing and add a try block in that section of the code.
If you have custom exceptions that you would like to handle before returning the response and possibly modifying the response, maybe even raising an HTTPException, create a Custom Exception Handler.
Tip
You can still raise exceptions including HTTPExceptionbefore the yield. But not after.
The sequence of execution is more or less like this diagram. Time flows from top to bottom. And each column is one of the parts interacting or executing code.
Info
Only one response will be sent to the client. It might be one of the error responses or it will be the response from the path operation.
After one of those responses is sent, no other response can be sent.
Tip
This diagram shows HTTPException, but you could also raise any other exception for which you create a Custom Exception Handler.
If you raise any exception, it will be passed to the dependencies with yield, including HTTPException, and then again to the exception handlers. If there's no exception handler for that exception, it will then be handled by the default internal ServerErrorMiddleware, returning a 500 HTTP status code, to let the client know that there was an error in the server.