编程语言
首页 > 编程语言> > java中的try-catch-finally块

java中的try-catch-finally块

作者:互联网

根据我的理解,我希望遵循最终释放资源的最佳实践,以防止任何连接泄漏.这是我在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;
}

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

解决方法:

你的理解是正确的. dynamoBD.shutdown()将始终在返回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);
    }
}

并用它作为

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();
}

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

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

标签:java,try-catch-finally,amazon-dynamodb,program-flow
来源: https://codeday.me/bug/20190715/1466297.html