Swallowing exceptions during disconnect / shutdown

Suppose I have code like this:

try {
    doSomethingWithTheConnection(connection)
} finally {
    connection.disconnect()
}

What should happen if a function inside connection.disconnect() throws an exception? “Disconnecting” is part of a shutdown procedure here. If an error happens during a shutdown, what can you do, besides logging the incident? Is it valid in such a case to swallow the exception to make sure shutdown continues? Is there an idiomatic way for handling such a case?

1 Like

It depends on your situation. Depending on what you actually do in shutdown you are probably able to recover from most exceptions and continue with the rest of the shutdown, eg. if a connection is already closed (Idk, maybe due to a disconect) you can probably ignore that and just continue with the rest of the shutdown.
In any case I think you should at least log every exception instead of just ignoring it.

Not that I’m aware of. I would suggest to clean up all resources in their own functions maybe. That way you can easily continue with closing the next one if one part of the shutdown fails. Also try to keep the shutdown code as simple as possible. Especially for resources that don’t close automatically if your program terminates this is helpful because less/simpler code equals less bugs :wink:

1 Like