做最后尝试是有意义的没有“捕获” [英] Does it make sense to do "try-finally" without "catch"?

查看:79
本文介绍了做最后尝试是有意义的没有“捕获”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到一些这样的代码:

I saw some code like this:

    try
    {
        db.store(mydata);
    }
    finally
    {
        db.cleanup();
    }

我以为 try 应该有一个 catch

为什么这段代码这样做?

Why does this code do it this way?

推荐答案

如果您希望当前执行的方法仍然抛出异常,同时适当地清除资源,这是有用的。以下是处理来自调用方法的异常的具体示例。

This is useful if you want the currently executing method to still throw the exception while allowing resources to be cleaned up appropriately. Below is a concrete example of handling the exception from a calling method.

public void yourOtherMethod() {
    try {
        yourMethod();
    } catch (YourException ex) {
        // handle exception
    }
}    

public void yourMethod() throws YourException {
    try {
        db.store(mydata);
    } finally {
        db.cleanup();
    }
}

这篇关于做最后尝试是有意义的没有“捕获”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆