NullPointerException for Query - java

I got NullPointerException error after using toString().substring() . I need to use this method. Help me please. I am not very sure i can use that method inside the query.
Orginal
String selectItemMasDetl="select MMITNO,MMITDS,MMALUN,MMSPUN from"+DBConnect.SCHEMA+".mitmas where MMCONO=888 and MMITNO="+ItemNo+"'";
Use ToString().substring()
String selectItemMasDetl="select MMITNO,MMITDS,MMALUN,MMSPUN from"+DBConnect.SCHEMA+".mitmas where MMCONO=888 and MMITNO="+ItemNo.toString().substring(0,4)+"'";
error log
java.lang.NullPointerException
[12/13/11 16:24:28:594 SGT] a6cc007 SystemErr R at com.------erp.report.stocklotsalesreport.StockLotSalesReportGet.getItemMasDetl
ANS:
selectItmMas="select MMITNO,MMITDS,MMALUN,MMSPUN from "+DBConnect.SCHEMA+".mitmas where MMCONO=888 and MMITNO like '"+ salesRecordListTO.getItemNo().trim() +"%'";
I use like operator and pass parameter instead of using trim. Now i get the result i want.
Thank you so much guys.

It means that at least in some cases either ItemNo or, DBConnect or the returned value of the toString() (as suggested) is null. The problem is that you don't have a stack trace, and so you can't be sure where the error is thrown. It could be even on another line, for what we (don't) know now.
Try to wrap with a try catch the relevant lines and print a stack trace, check the line of code where is happening, and post here again. Here is how:
try {
//code throwing exception
} catch (Exception ex) {
ex.printStackTrace();
}
Side note: seems that you need a space after the from, also you're closing a single quote, but I don't see the opening. Below, for reference, your code, only reformatted, not fixed:
String selectItemMasDetl = "select MMITNO,MMITDS,MMALUN,MMSPUN from"
+ DBConnect.SCHEMA + ".mitmas where MMCONO=888 and MMITNO="
+ ItemNo.toString().substring(0,4) + "'";

NullPointerExeption means that ItemNo is null, so when trying to use ItemNo.toString(), it will be interpreted as null.toString() which will throw the exception.

A check on null is one possibility (the easiest), see answer of Stivlo.
Depending on how quick the query is a count query can be done also, if count ==0 don't bother to do the real query.
Oops, sorry, not reading good: the null exception is already in building the query string. Well maybe this is of use in your next nullpointer exception :)
StringBuilder might be a solution, but than I think you'll get an invalid querystring, just use Stivlo's answer.

Related

Can log4j's error method print stack trace without string argument?

In regards to Log4j v2, I'd like to call log.error(exceptionTypeObj) and have the stack trace printed to my logfile instead of exceptionTypeObj.toString(). Is that possible?
I'd rather write code like log.error(e) and be done with it.
It's error prone and redundant for me to keep writing something like log.error("error", exceptionTypeObj).
The String parameter is redundant because you are not using it for the correct purpose. An Exception will tell you what error occurred but it won't tell you what you were trying to do when it happened. That is why you should always provide the string. Provide a String that says something like "Error occurred while attempting to update the user profile for user {}", and then provide the user name or id.
Without the String parameter you are forcing your support staff to call engineering to find out what the exception means and what they should do about it.

Can searchResponse.getHits().getHits(); throw nullpointer exception

We are getting a nullpointerexception at searchResponse.getHits().getHits();
I'm totally new to elastic search and don't know how it works but need to analyse this issue.
Let me know if it throws nullpointerexception in any case ?
If it throws how to handle this ?
Looking at the code of InternalSearchResponse, it looks like hits gets initialised with SearchHits.empty() even if the response is empty.
For the other cases, it always gets initialised with new. You can have a look at the source code here.
I had the same exception after an update from 7.4 to 7.17.
It seems that the hits variable of the internalResponse can be NULL, at least in 7.17.1 - could be related to HL request option ignoreUnavailable set to FALSE, and/or queering a no longer existing index.
searchResponse.getHits() can return NULL!

How to solve when value 1 using e.getMessage() in Java

Anyone know why Exception().getMessage return to 1? What does it mean? I have tried to find the answer but nothing found, thank.
Use e.printStackTrace instead of e.getMessage() in case of exception. It will display all the information required to debug the issue, whereas printing only the message of the exception doesn't tell you almost anything.
If using a logger, use the form that accepts an exception/throwable, usually of the form logger.error("Custom error message", e);, and the stacktrace will be printed.

How to catch Neo4j TransientException: LockClient

I often get this kind of Exception
Exception in thread "main" org.neo4j.driver.v1.exceptions.TransientException: LockClient[21902] can't wait on resource RWLock[NODE(1423923), hash=286792765] since => LockClient[21902] <-[:HELD_BY]- RWLock[NODE(1419986), hash=869661492] <-[:WAITING_FOR]- LockClient[21905] <-[:HELD_BY]- RWLock[NODE(1423923), hash=286792765]
when I run Neo4j queries in my Java application. Now, this question has a good answer to the reason why this error occurs, and I can't do anything to improve my queries: I just need them as they are.
My question is: how can I catch this kind of exception? It occurs at this line of my code:
session.run(query, parameters);
but the Javadoc doesn't show any apparent Exception to be catched with a try-catch block.
Thanks in advance.
This is because TransientException is a runtime exception (E.G. a subclass of Java.lag.RuntimeException). It is not required to be in the method signature, and you are not required to put he method in a Try...Catch block. Try putting that line within a try...catch block and you should not get that exception anymore. How you handle it depends on the nature of your application. You could print a warning to log, and then error in the application, or even keep trying until the code worked.
Edit: after reading the answer you linked, I understand why you are getting these exceptions. I would put a Thread.sleep() in the catch block, then attempt the query again, in which case the error should go away. But then again, I am in no way a Neo4j expert so take my advice with a grain (truckload ) of salt
Edit 2: your code should look somewhat like this:
for(Query query : queries){
boolean flag = false;
while(!flag){
try{
query.execute();
flag = true;
} catch (TransientException e){
log("Retrying query "+query);
Thread.sleep(1*1000); //1 second
}
}
}

Java - ignore exception and continue

For my Java application, I am creating an instance of a user information object and populating it with a service that I don't control the source for.
The code looks like this:
// username given as parameter
UserInfo ui = new UserInfo();
try {
DirectoryUser du = LDAPService.findUser(username);
if (du!=null) {
ui.setUserInfo(du.getUserInfo());
}
} catch (Exception e) {
// Whatever
}
If LDAPService.findUser() can't locate a user, it will throw a NullPointerException and grind the rest of my application to a stop. It's okay if the user information isn't populated, so I want to be able to continue without causing everything else to start throwing exceptions.
Is there a way to do this?
I've upvoted Amir Afghani's answer, which seems to be the only one as of yet that actually answers the question.
But I would have written it like this instead:
UserInfo ui = new UserInfo();
DirectoryUser du = null;
try {
du = LDAPService.findUser(username);
} catch (NullPointerException npe) {
// It's fine if findUser throws a NPE
}
if (du != null) {
ui.setUserInfo(du.getUserInfo());
}
Of course, it depends on whether or not you want to catch NPEs from the ui.setUserInfo() and du.getUserInfo() calls.
You could catch the NullPointerException explicitly and ignore it - though its generally not recommended. You should not, however, ignore all exceptions as you're currently doing.
UserInfo ui = new UserInfo();
try {
DirectoryUser du = LDAPService.findUser(username);
if (du!=null) {
ui.setUserInfo(du.getUserInfo());
}
} catch (NullPointerException npe) {
// Lulz # your NPE
Logger.log("No user info for " +username+ ", will find some way to cope");
}
You are already doing it in your code. Run this example below. The catch will "handle" the exception, and you can move forward, assuming whatever you caught and handled did not break code down the road which you did not anticipate.
try{
throw new Exception();
}catch (Exception ex){
ex.printStackTrace();
}
System.out.println("Made it!");
However, you should always handle an exception properly. You can get yourself into some pretty messy situations and write difficult to maintain code by "ignoring" exceptions. You should only do this if you are actually handling whatever went wrong with the exception to the point that it really does not affect the rest of the program.
It's generally considered a bad idea to ignore exceptions. Usually, if it's appropriate, you want to either notify the user of the issue (if they would care) or at the very least, log the exception, or print the stack trace to the console.
However, if that's truly not necessary (you're the one making the decision) then no, there's no other way to ignore an exception that forces you to catch it. The only revision, in that case, that I would suggest is explicitly listing the the class of the Exceptions you're ignoring, and some comment as to why you're ignoring them, rather than simply ignoring any exception, as you've done in your example.
You are actually ignoring exception in your code. But I suggest you to reconsider.
Here is a quote from Coding Crimes: Ignoring Exceptions
For a start, the exception should be logged at the very least, not
just written out to the console. Also, in most cases, the exception
should be thrown back to the caller for them to deal with. If it
doesn't need to be thrown back to the caller, then the exception
should be handled. And some comments would be nice too.
The usual excuse for this type of code is "I didn't have time", but
there is a ripple effect when code is left in this state. Chances are
that most of this type of code will never get out in the final
production. Code reviews or static analysis tools should catch this
error pattern. But that's no excuse, all this does is add time to the
maintainance and debugging of the software.
Even if you are ignoring it I suggest you to use specific exception names instead of superclass name. ie., Use NullPointerException instead of Exception in your catch clause.
You can write a try - catch block around the line you want to have ignored.
Like in the example code of yours. If you just continue your code below the closing bracket of the catch block everythings fine.
LDAPService should contain method like LDAPService.isExists(String userName) use it to prevent NPE to be thrown. If is not - this could be a workaround, but use Logging to post some warning..
Printing the STACK trace, logging it or send message to the user, are very bad ways to process the exceptions. Does any one can describe solutions to fix the exception in proper steps then can trying the broken instruction again?

Categories

Resources