Autocloseable类不会调用默认的close方法

时间:2016-01-26 07:57:40

标签: java exception autocloseable

我有这段代码:

public class Main {

    public static void main(String[] args) {
        int a, b = 0;
        a = 5;

        try {
            Resource first = new Resurs(1);
            Resource second = new Resurs(2);
            System.out.println("I will cause exception");
            a /= b;
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

主要课程:

I am resource. My number is 1.
I am resource. My number is 2.
I will cause exception.
java.lang.ArithmeticException: / by zero

我想知道为什么我得到这个输出:

I am resource. My number is 1.
I am resource. My number is 2.
Closing...
Closing...
I will cause exception.
java.lang.ArithmeticException: / by zero

而不是:

   public ActionResult Find()
    {
        DirectoryEntry entry = new DirectoryEntry(
                      "LDAP://example..");

        DirectorySearcher searcher;
        SearchResultCollection results;

        searcher = new DirectorySearcher(entry);

        searcher.Filter = "(&(objectClass=user)(displayname=*))";
        searcher.SearchScope = SearchScope.Subtree;

        using (searcher)
        {
            results = searcher.FindAll();

            foreach (SearchResult result in results)
            {
               string searchOK = result.Properties["displayname"][0].ToString();
               objects.Add(searchOK);
            }
        }
        return View();
    }

1 个答案:

答案 0 :(得分:10)

因为您没有使用try-with-resources。仅使用AutoCloseable调用try/catch,而不是使用常规try(Resource first = new Resource(1); Resource second = new Resource(2)) { // .. whatever } 语句。

正确的模式是

sample.xls
Sample2.xls
Sample3.xls