views:

139

answers:

2

I've a line in my Lucene code:

try
{
    searcher.GetIndexReader();
}
catch(Exception ex)
{
    throw ex;
}
finally
{
    if (searcher != null)
    {
        searcher.Close();
    }
}

In my finally clause, when I execute searcher.Close(), will it also execute searcher.GetIndexReader().Close behind the scenes?

Or do I need to explicitly call searcher.GetIndexReader().Close() method to close IndexReader??

Thanks for reading.

+1  A: 

Sorry, it's tough to understand what is the type of searcher in your snippet and how it was constructed. But you should not close the the index reader with searcher.GetIndexReader().Close(). The searcher.Close() will close all resources associated with it and index reader as well IF searcher IS NOT IndexSearcher instance constructed with IndexSearcher(IndexReader r). In that case you have to close index reader manually.

reta
thanks for ur comments...am creating searcher like this:searcher = new IndexSearcher(myIndexDir);so in this case, how shall i close index reader?
Steve Chapman
If you are creating searcher from directory, closing searcher is good enough. It will internally close the reader.
Shashikant Kore
thanks shashikant for ur answer!
Steve Chapman
A: 

First of all, code like this is always a bad idea:

try {
    // Do something
} catch(Exception ex) {
    throw ex;  // WRONG
}

You're just masking the source of the exception, and still throwing. Better just to delete those lines.

If you didn't create the IndexReader yourself, you don't need to close it yourself. Chances are high that you don't need to use the method getIndexReader at all.

Also, unless you're assigning to searcher within the try block, there's no need to check if it's null, since there's no way it could get a null value.

Here's an example of what your code should look like:

String myIndexDir = "/my/index/dir";

IndexSearcher searcher = new IndexSearcher(myIndexDir);
try { 
    // Do something with the searcher
} finally { 
    searcher.close(); 
}
itsadok