It's well agreed that InterruptedException
should not be swallowed in general; it is a request that a thread cleanup and terminate its work.
How should the API design of a given abstraction I
handle InterruptedException
if a subset of its implementations may throw InterruptedException
?
More concretely, imagine a Datasource
with InMemoryDatasource
and NetworkDatasource
implementations. The latter includes a blocking call over a network, and thus may throw InterruptedException
. This means InterruptedException
should be declared on the Datasource
interface.
This seems appropriate - it's a data source, you don't know where the data is coming from, so it might block and clients should handle InterruptedException
as a result.
But it brings something else to mind - why don't we see more InterruptedException
s being declared in APIs?
For example:
- The JDBC API doesn't declare it, even though it makes blocking calls.
- The PostgreSQL JDBC driver swallows such exceptions and rethrows them as
SQLException
s.. - It looks like the MongoDB driver wraps it in a RuntimeException.
- The AWS SDK doesn't throw it (but at least sets the interrupted flag).
It seems general to not rethrow InterruptedException
in APIs.
As an API designer, how is it best to deal with InterruptedException
?