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.
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.
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();
}
Related
Need a bit quick help with Kotlin. Here is the pseudocode: When there is a “specialCase” error, throw the exception and Log this exception as “Info”. This is the if statement I have. Does this look like a good approach?
if (error.contains (specialCase))
{
throw specialCaseDoesNotExistException
}
LOGGER.info("WriteSpecialCaseasInfoandNOTError")
Either you log before throwing or you could combine it into a single statement using also (reference):
if (error.contains (specialCase)) {
LOGGER.info("WriteSpecialCaseasInfoandNOTError")
throw specialCaseDoesNotExistException
}
if (error.contains (specialCase)) {
throw specialCaseDoesNotExistException.also {
LOGGER.info("WriteSpecialCaseasInfoandNOTError")
}
}
I am trying to Delete a object on the screen and once it's gone check if it's still in the webpage to make sure it's gone.
By doing this :
WebElement objectToDelete = GetElementFromDriver("object-to-delete");
objectToDelete.delete(); //in some other way which results in it being gone.
objectToDelete = GetElementFromDriver("object-to-delete");
I've tried surrounding it with try & catch but I keep getting an exception.
Ex:
try{
objectToDelete = GetElementFromDriver("object-to-delete");
} catch(Exception e){
return null;}
What am I missing? Is it even possible to do what I want, perhaps in a different way?
Thanks!!
If needed I'll add my chrome/driver/selenium versions although I believe they're not relevant.
Did you try WebDriverWait "until" and "until_not" methods ?
Eg: http://selenium-python.readthedocs.io/waits.html.
The solution -
public static boolean isElementPresent throws Exception(String elementName, WebElement father){
try{
Utils.GetElementFromElement(By.className(elementName), 5, father);
return true;
} catch(NoSuchElementException e){
return false;
}
}
see here: The proper way to do exception handling
say this code:
function changeBookAuthor(int $id, string $newName){
if(!$newName){
throw new MyAppException('No author name was provided');
}
$book = Books::find($id);
if(!$book){
throw new MyAppException('The provided book id could not be found');
}
//..
}
i want to change that to:
function changeBookAuthor(int $id, string $newName){
if(!$newName){
throw new MyAppException('No author name was provided', <SOMEVERYRANDOMNUMBER>);
}
$book = Books::find($id);
if(!$book){
throw new MyAppException('The provided book id could not be found', <SOMEVERYRANDOMNUMBER>);
}
//..
}
can intellij help me in selecting random numbers?
I personally use different types of Exception instead of exception code.
For example:
try{
...
} catch (PDOException e1){
// Show a message that we could not do SQL work
} catch (NumberFormatException e2){
// Show a message that input was not a valid number
} catch (Exception e){
// I'm not sure what was wrong but definitely there was some thing wrong
}
But if you still want random numbers, go to https://www.random.org, there are some number generators, copy values and define them as constants in your code (i guess that you are using PHP)
I made a test class against the repository methods shown below:
public void AddFile<TFileType>(TFileType FileToAdd) where TFileType : File
{
try
{
_session.Save(FileToAdd);
_session.Flush();
}
catch (Exception e)
{
if (e.InnerException.Message.Contains("Violation of UNIQUE KEY"))
throw new ArgumentException("Unique Name must be unique");
else
throw e;
}
}
public void RemoveFile(File FileToRemove)
{
_session.Delete(FileToRemove);
_session.Flush();
}
And the test class:
try
{
Data.File crashFile = new Data.File();
crashFile.UniqueName = "NonUniqueFileNameTest";
crashFile.Extension = ".abc";
repo.AddFile(crashFile);
Assert.Fail();
}
catch (Exception e)
{
Assert.IsInstanceOfType(e, typeof(ArgumentException));
}
// Clean up the file
Data.File removeFile = repo.GetFiles().Where(f => f.UniqueName == "NonUniqueFileNameTest").FirstOrDefault();
repo.RemoveFile(removeFile);
The test fails. When I step in to trace the problem, I found out that when I do the _session.flush() right after _session.delete(), it throws the exception, and if I look at the sql it does, it is actually submitting a "INSERT INTO" statement, which is exactly the sql that cause UNIQUE CONSTRAINT error. I tried to encapsulate both in transaction but still same problem happens. Anyone know the reason?
Edit
The other stay the same, only added Evict as suggested
public void AddFile<TFileType>(TFileType FileToAdd) where TFileType : File
{
try
{
_session.Save(FileToAdd);
_session.Flush();
}
catch (Exception e)
{
_session.Evict(FileToAdd);
if (e.InnerException.Message.Contains("Violation of UNIQUE KEY"))
throw new ArgumentException("Unique Name must be unique");
else
throw e;
}
}
No difference to the result.
Call _session.Evict(FileToAdd) in the catch block. Although the save fails, FileToAdd is still a transient object in the session and NH will attempt to persist (insert) it the next time the session is flushed.
NHibernate Manual "Best practices" Chapter 22:
This is more of a necessary practice than a "best" practice. When
an exception occurs, roll back the ITransaction and close the ISession.
If you don't, NHibernate can't guarantee that in-memory state
accurately represents persistent state. As a special case of this,
do not use ISession.Load() to determine if an instance with the given
identifier exists on the database; use Get() or a query instead.
I've got a rule like this:
declaration returns [RuntimeObject obj]:
DECLARE label value { $obj = new RuntimeObject($label.text, $value.text); };
Unfortunately, it throws an exception in the RuntimeObject constructor because $label.text is null. Examining the debug output and some other things reveals that the match against "label" actually failed, but the Antlr runtime "helpfully" continues with the match for the purpose of giving a more helpful error message (http://www.antlr.org/blog/antlr3/error.handling.tml).
Okay, I can see how this would be useful for some situations, but how can I tell Antlr to stop doing that? The defaultErrorHandler=false option from v2 seems to be gone.
I don't know much about Antlr, so this may be way off base, but the section entitled "Error Handling" on this migration page looks helpful.
It suggests you can either use #rulecatch { } to disable error handling entirely, or override the mismatch() method of the BaseRecogniser with your own implementation that doesn't attempt to recover. From your problem description, the example on that page seems like it does exactly what you want.
You could also override the reportError(RecognitionException) method, to make it rethrow the exception instead of print it, like so:
#parser::members {
#Override
public void reportError(RecognitionException e) {
throw new RuntimeException(e);
}
}
However, I'm not sure you want this (or the solution by ire_and_curses), because you will only get one error per parse attempt, which you can then fix, just to find the next error. If you try to recover (ANTLR does it okay) you can get multiple errors in one try, and fix all of them.
You need to override the mismatch and recoverFromMismatchedSet methods to ensure an exception is thrown immediately (examples are for Java):
#members {
protected void mismatch(IntStream input, int ttype, BitSet follow) throws RecognitionException {
throw new MismatchedTokenException(ttype, input);
}
public Object recoverFromMismatchedSet(IntStream input, RecognitionException e, BitSet follow) throws RecognitionException {
throw e;
}
}
then you need to change how the parser deals with those exceptions so they're not swallowed:
#rulecatch {
catch (RecognitionException e) {
throw e;
}
}
(The bodies of all the rule-matching methods in your parser will be enclosed in try blocks, with this as the catch block.)
For comparison, the default implementation of recoverFromMismatchedSet inherited from BaseRecognizer:
public Object recoverFromMismatchedSet(IntStream input, RecognitionException e, BitSet follow) throws RecognitionException {
if (mismatchIsMissingToken(input, follow)) {
reportError(e);
return getMissingSymbol(input, e, Token.INVALID_TOKEN_TYPE, follow);
}
throw e;
}
and the default rulecatch:
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}