The first piece of advice; catch stuff only if you plan on handling it. And by handling I don't mean printing stuff on the console and carrying on your merry way. One logical use case can be a retry-logic. If you plan on trying to connect to a host with a retry-counter, you would normally catch the connection exception, increase the failure count and try again.
Also, make sure you always close resources in the finally
block since that's the only block which is guaranteed to be executed. So either you end up having try catch for each close
method call or end up skipping closing a few resources. Since closing resources is a pretty repetitive task, a lot of folks end up using utility classes like the one posted below:
class Utils {
private static final Logger log = Logger.getLogger(Utils.class.getName());
/**
* Close a list of AutoCloseable objects quietly. Works for pretty much all types of resources. But works only with
* Java 1.7+
*
* @param closeables
*/
public static void closeQuietly(AutoCloseable... closeables) {
for (final AutoCloseable resource : closeables) {
try {
if (resource != null)
resource.close();
} catch (final Exception e) {
log.log(Level.WARNING, "Exception when closing resource", e);
}
}
}
/**
* Close a bunch of Closeable objects silently; doesn't work for DB resources like ResultSet, Connection etc.
*
* @param closeables
*/
public static void closeQuietly(Closeable... closeables) {
for (final Closeable resource : closeables) {
try {
if (resource != null)
resource.close();
} …