java中的try-catch-finally块

Cha*_*ndz 3 java program-flow try-catch-finally amazon-dynamodb

根据我的理解,我希望遵循最终释放资源的最佳实践,以防止任何连接泄漏.这是我在HelperClass中的代码.

public static DynamoDB getDynamoDBConnection()
{   
    try
    {
        dynamoDB = new DynamoDB(new AmazonDynamoDBClient(new ProfileCredentialsProvider()));
    }
    catch(AmazonServiceException ase)
    {
        //ase.printStackTrace();
        slf4jLogger.error(ase.getMessage());
        slf4jLogger.error(ase.getStackTrace());
        slf4jLogger.error(ase);
    }
    catch (Exception e)
    {
        slf4jLogger.error(e);
        slf4jLogger.error(e.getStackTrace());
        slf4jLogger.error(e.getMessage());
    }
    finally
    {
        dynamoDB.shutdown();
    }
    return dynamoDB;
}
Run Code Online (Sandbox Code Playgroud)

我的疑问是,既然finally块将被执行,无论如何,dynamoDB将返回空连接,因为它将在finally块中关闭然后执行return语句?TIA.

aio*_*obe 10

你的理解是正确的.dynamoBD.shutdown()将永远执行之前return dynamoDB.

我不熟悉你正在使用的框架,但我可能会按如下方式组织代码:

public static DynamoDB getDynamoDBConnection()
        throws ApplicationSpecificException {   
    try {
        return new DynamoDB(new AmazonDynamoDBClient(
                                    new ProfileCredentialsProvider()));
    } catch(AmazonServiceException ase) {
        slf4jLogger.error(ase.getMessage());
        slf4jLogger.error(ase.getStackTrace());
        slf4jLogger.error(ase);
        throw new ApplicationSpecificException("some good message", ase);
    }
}
Run Code Online (Sandbox Code Playgroud)

并用它作为

DynamoDB con = null;
try {
    con = getDynamoDBConnection();
    // Do whatever you need to do with con
} catch (ApplicationSpecificException e) {
    // deal with it gracefully
} finally {
    if (con != null)
        con.shutdown();
}
Run Code Online (Sandbox Code Playgroud)

您还可AutoCloseable以为您的dynamoDB连接(shutdown内部调用close)创建一个包装器并执行

try (DynamoDB con = getDynamoDBConnection()) {
    // Do whatever you need to do with con
} catch (ApplicationSpecificException e) {
    // deal with it gracefully
}
Run Code Online (Sandbox Code Playgroud)