NullPointerException when trying to submit a query - java

I am trying to execute java program but it seems the current code is returning null pointer exception on this piece of code:
IntegerDesc yearOfBuildDesc =
(IntegerDesc) myConcept.getAllAttributeDescs().get("yearOfBuild");
try {
query.addAttribute(yearOfBuildDesc,
yearOfBuildDesc.getAttribute("yearOfBuild"));
}
catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Do you know where the problem might come from?

Probably one of the following:
myConcept is null, so .getAllAttributeDescs() falls over.
myConcept.getAllAttributeDescs() returns null, so .get("yearOfBuild") falls over.
myConcept.getAllAttributeDescs().get("yearOfBuild") returns null, leading yearOfBuildDesc to be null when you call getAttribute on it, which causes an exception.
query is null, causing .addAttribute(...) to fall over.
Something inside the getAllAttributeDescs method causes a null pointer exception when invoked.
Something inside the get method causes a null pointer exception when invoked.
Something inside the addAttribute method causes a null pointer exception when invoked.
Something inside the getAttribute method causes a null pointer exception when invoked.
Your initial code throws a ParseException, the call to whose printStackTrace method then throws a null pointer exception (unlikely).
In general, when hunting down null pointer exceptions, you should look for problems with:
Select expressions (i.e. x.y) - can the x be null?
Method calls - can the method throw a null pointer exception?
I've excluded the possibility that e is null here, since it's the exception you just caught.

yearOfBuildDesc.getAttribute("yearOfBuild");
Above line will throw NullPointerException if yearOfBuildDesc is null, add a null check.

yearOfBuildDesc might be null. Test before using it in the try catch
myConcept might also be null, check also.

Related

Catch exception in Java parameters

How can I catch in exception in Java parameters
Just one example, in code like this
MyClass obj = null;
logger.info("the field is " + obj.field);
a null pointer exception is thrown. Is there a way to automatically do this:
MyClass obj = null;
try {
logger.info("the field is " + obj.field);
} catch(Exception e) {}
Perhaps using Spring AOP, annotations, etc?
Edit: I want something that will catch any exception, so that I never have an exception thrown from a line of code that tries to log.
No there isn't. And you shouldn't do wrap your code in try catch. This may avoid you some runtime exceptions but also could hide real code issues. You could use the Null Object pattern. You create a marker class with empty fields and if a value in your code should be null you assign it to an instance of this marker class. That should work for code under your control, however it doesn't guarantee third party libraries wouldn't throw NPE.
Edit: I want something that will catch any exception, so that I never have an exception thrown from a line of code that tries to log.
That can never be achieved. What you are asking for essentially is a try catch block at the start to end of the main method. Even though you still can get exceptions from other threads for example

how can null exception enter try-catch branch?

My java code throws exception e which is null (debug shows e==null)
How can the code catch this at:
} catch (IOException e) {
e.printStackTrace();
}
If e is null how can it have a type?
Two ideas occur to me:
1) What most debuggers display is e.toString(). If you have an exception object whose toString() is returning null (or "null"), that might explain what you're seeing. What type does the debugger say e is?
2) Another possibility is that your source code doesn't match the class currently executing, and you're at a different line than you think you are. I've been caught out that way.

How does `try / catch` work in details

I would like to the innards of how does try {} catch {} block and stack traces work.
I was reading this great article about exception handling anti-patterns and found the following paragraph:
catch (NoSuchMethodException e) {
throw new MyServiceException("Blah: " +
e.getMessage());
}
This destroys the stack trace of the original exception, and is always wrong.
After that I realized that I don't really know how try/catch works. My understanding is the following. Consider the example:
void top() {
try {
f();
} catch (MyException ex) {
handleIt();
} finally {
cleanup();
}
}
void f() {
g();
}
void g() {
throw new MyException();
}
When I call top(), the call chain top -> f -> g
leaves two stack frames on the call stack (for top and f functions). When the exception is raised in g,
the program bubbles up the execution stack until it finds try/catch block that handles the exception. Meanwhile it frees the stack frames and attach stack trace information to some "magic" object that can be passed to catch and the stack trace can be printed.
How does it know that the called function is "surrounded" with the try/catch block? Is this information bound to the stack frame? Like, a pointer to error handling block (some switch selecting a matching catch block), and a pointer to finally block? Why e.getMessage() is destructive in the example above (see the comments)?
Note, I know how to use try/catch and exceptions, I want to know how does it work inside.
"How does it know that the called function is "surrounded" with the try/catch block?"
The code of each method contains Exception Table which describes all try-catch blocks of that method.
When a procedure (function, method) is called, the current stack frame is appended with the address of the calling instruction, so as to restore execution of that frame at the correct instruction (next after calling instruction).
When a throw statement is executed, the JVM examines each stack frame to find out if that frame can handle the exception. It can if its method contains a try-catch block which contains the calling instruction, and the type of block's exception is a supertype (or the same as) of the thrown exception. If such a frame is found, the frame restores its execution from the instruction pointed to from the try-catch block.
When an exception is thrown, the complete calling-stack information is attached not to some magic object, but to the exception object that is created. This doesn't happen while the exception "bubbles up" - it happens when it is created and it always contains the full call-chain.
The called function doesn't need to know it is surrounded by a try-catch-block, it just creates an Exception-object that contains the call-chain and passes it up to the calling method. This method has to decide wether it handles the Exception because it is caught by some catch-clause or if it passes it further up. Exception that aren't caught bubble up till they reach the top of the calling-chain and the VM handles them - usually by printing the stack-trace and terminating.
Regarding the e.getMessage-example:
The full stack-information is contained only in the original exception. In the given example that original Exception object e is discarded, only the contained message is passed on to a newly created Exception-object. And that Exception only "knows" its own calling stack, so the original information attached to e is lost.
Lower level method just throws exception and we should handle them in upper level. Consider your example. It should like this
void top() {
try {
f();
} catch (MyException ex) {
handleIt();
} finally {
cleanup();
}
}
void f() throws MyException {
try{
g();
}catch(MyException e){
throws new MyException("Error in g()",e);
}
}
void g() throws MyException{
throw new MyException();
}
Exception are propagated up the call stack, from the method that initially throws it, until a method in the call stack catches it. If a method A calls B, and B calls C then the call stack looks like this:
A
B
C
When method C returns the call stack only contains A and B.
Exception are propagated up the call stack, from the method that initially throws it, until a method in the call stack catches it.
When an exception is thrown the method stops execution right after the "throw" statement. Any statements following the "throw" statement are not executed. The program resumes execution when the exception is caught somewhere by a "catch" block.
If a method calls another method that throws checked exceptions, the calling method is forced to either pass the exception on, or catch it. Catching the exception is done using a try-catch block.If no exception is thrown by any of the methods called or statements executed inside the try-block, the catch-block is simply ignored.If an exception is thrown inside the try-block, for instance from the divide method, the program flow of the calling method, callDivide, is interrupted just like the program flow inside divide. The program flow resumes at a catch-block in the call stack that can catch the thrown exception.
If an exception is thrown inside the catch-block and that exception is not caught, the catch-block is interrupted just like the try-block would have been.
http://tutorials.jenkov.com/java-exception-handling/basic-try-catch-finally.html
https://www.geeksforgeeks.org/flow-control-in-try-catch-finally-in-java/

What is the meaning of Possible null pointer dereference in findbug?

I am using Sonar and I have got this kind of violation from it for a peace of my code:
Correctness - Possible null pointer dereference
Has anyone know about this rule in findbugs? I searched a lot but I can not find a good sample code (in Java) which describe this rule, unfortunately findbugs site did not have any sample code or good description about this rule.
Why does this violation appear?
a sample code is something like this.
String s = null ;
if (today is monday){
s = "Monday" ;
else if (today is tuesday){
s = "Tuesday" ;
}
System.out.println(s.length()); //Will throw a null pointer if today is not monday or tuesday.
It says here
NP: Possible null pointer dereference (NP_NULL_ON_SOME_PATH)
There is a branch of statement that, if executed, guarantees that a null value will be dereferenced, which would generate a NullPointerException when the code is executed. Of course, the problem might be that the branch or statement is infeasible and that the null pointer exception can't ever be executed; deciding that is beyond the ability of FindBugs.
If you would have posted some code it would be easier to answer.
EDIT I don't see a lot of documentation but here is one example! Hope this helps!
Okay
This is two simple Examples :
First one gives a : Possible null pointer dereference
1. Error
ArrayList a = null;
a.add(j, PointSet.get(j));
// now i'm trying to add to the ArrayList
// because i'm giving it null it gives me the "Possible null pointer dereference"
2. No Error
ArrayList a = new ArrayList<>();
a.add(j, PointSet.get(j));
// adding elements to the ArrayList
// no problem
Simple ?
I got this issue with the following piece of code:-
BufferedReader br = null;
String queryTemplate = null;
try {
br = new BufferedReader(new FileReader(queryFile));
queryTemplate = br.readLine();
} catch (FileNotFoundException e) {
// throw exception
} catch (IOException e) {
// throw exception
} finally {
br.close();
}
Here, the br BufferedReader can be null in br.close(). However it can only be null if new BufferedReader() fails, in which case we are throwing the relevant exceptions.
This is thus a false warning. Findbugs docs mention the same:-
This may lead to a NullPointerException when the code is executed.
Note that because FindBugs currently does not prune infeasible
exception paths, this may be a false warning.
In simple language, if a variable value is assigned as null, and you try to access it with any inbuilt method like add/get. Then null pointer dereference issue comes with SONAR. Because there are changes for it go null, and throw null pointer exception. Try to avoid it if possible.
For example:
File file=null;
file.getName();
will throw "Possible null pointer dereference"
It may not happen directly as mentioned in the example, it can be unintentionally.

Handling a null pointer exception in a webservice

I am writing a webservice, where in the webservice read a bunch of records one by one, process them and store them into the database.
If for a record, a field is missing, then an error object is created with the missing information and sent back as response.
Inspite of all null checks that I have done, there might be some null pointer exceptions hanging around as I have no control over the records coming in to the service.
If say for 45th record, a NPE occurs, the service breaks. Instead of this, I want the service to proceed and process the next record.
So, is it ok if I catch the NPE in such cases or any there any better alternatives.I have read that catching NPE isn't recommended but not sure if I have to break the rule here.
If you cannot stop the NullPointerException with null checks, then the only alternative is to catch it. However, I cannot think of an instance where null checks cannot prevent a NullPointerException.
If a null pointer is expected, I see no problem catching the NullPointerException. I think it's cleaner than having 50 billion if not nulls...
Although, you should not catch NPEs in general, it is acceptable catching them if you know what you do. You should avoid catching NPEs and not rethrowing them in complex chains like
try {
a.getB().getC().getD();
} catch (NullPointerException e) {
// only the stack trace indicates where the exception occured
}
Let's say in the above example you expect the NPE to be thrown on getD(), try to refactor your code to
C c = a.getB().getC();
try {
c.getD();
} catch (NullPointerException e) {
// you know that either `c` is null or that the exception was thrown in `getD()`
}
My 2 cents... neverthesless, if you know that NPEs can occur inside the WS request you should guard it accordingly:
if (c != null) {
// do something (getD() can still throw a NPW)
c.getD();
} else {
}
If there are NPEs resulting from invalid records, and you have no control over the records, then your logic should attempt to validate the records before processing them. The best way to do this would be to loop over each record, checking for the valid format, keeping track of invalid rows. After validation, if any invalid rows exist, you can report them in a meaningful format back to the UI. Otherwise proceed with the actual processing.
List<String> invalidRows = new ArrayList<String>();
for each row {
if (row is missing x) {
invalidRows.add("Record " + rowNumber + " is missing X");
}
if (row is missing y) {
invalidRows.add("Record " + rowNumber + " is missing Y");
}
}
if (invalidRows.isEmpty()) {
//process
}
else {
format and return error message using data collected
}
(note that the use of a List<String> is a general example - you should store and then format this information in the way that makes the most sense for your situation.)
An alternative to this approach would be to do your validation and processing in the same loop, keeping track of invalid rows and processing valid ones. At the end, the UI could report how many succeeded and which failed.
Additionally, one might wrap web services in a last defense to make unhandled exceptions more manageable and consumable by the client UI, or at least easier for you to read:
#WebMethod(operationName = "myMethod")
public String myMethod() {
try {
//logic
return "done";
}
catch (Throwable error) {
//returns formatted String representing error - UI should check for this
return MyExceptionFormatter.formatUnhandled(error);
}
}
Your custom formatting would assemble a more meaningful String representing the exception, potentially in XML format. This all depends on what your client UI is expecting.

Categories

Resources