File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes how to avoid null pointer exception(URGENT PLEASE) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "how to avoid null pointer exception(URGENT PLEASE)" Watch "how to avoid null pointer exception(URGENT PLEASE)" New topic
Author

how to avoid null pointer exception(URGENT PLEASE)

reva oday
Greenhorn

Joined: Dec 18, 2005
Posts: 6
Hi

I need to avoid having null pointer exception...

As i am new bie to java programming i need urgent help from anyone...

look at the following functionality it is having try..catch ...part and if there is any error it is hanled by log messages we created.



the same function executes properly before one month with out having any exception..If there is any data to be extract comes with null it throws null pointer..I need to give the log message instead of getting null pointer...

i am in stuck to do it...please any one give vluable suggestions...
see the stack trace of some piece of error

Dec 14 14:40:31 Connected to tcp://localhost
Dec 14 14:40:31 Execute Status: 2
Dec 14 14:40:31 Extraction is about to start
Dec 14 14:40:31 Exception while running report REPORT381-389
java.lang.NullPointerException
at sen.extractor.Report.Extract(Report.java:176)
at sen.extractor.Extractor.Execute(Extractor.java:457)
at sen.extractor.Extractor.run(Extractor.java:583)
at java.lang.Thread.run(Thread.java:534)
Dec 14 14:40:31 Job failed to RUN and Notification sent and process is STOPPED
Dec 14 14:40:31 Setting Status to: ERROR

please help...

[EDIT by mw: Added Code Tags using original poster's indentation.]
[ December 20, 2005: Message edited by: marc weber ]
Ken Blair
Ranch Hand

Joined: Jul 15, 2003
Posts: 1078
So either "string" is null or "bundle" is null. Neither of which are declared or instantiated within the code you posted. I seriously suggest 1) code formatting that follows Java conventions and 2) using code tags so the formatting is kept when it's posted.
reva oday
Greenhorn

Joined: Dec 18, 2005
Posts: 6
string filename is getting null pointer exception...
as in stack what i provided..i need to catch the error with some error messages.

i havent idea of how to do...please help me..
Ken Blair
Ranch Hand

Joined: Jul 15, 2003
Posts: 1078
Originally posted by revathy oday:
string filename is getting null pointer exception...
as in stack what i provided..i need to catch the error with some error messages.

i havent idea of how to do...please help me..


FileName is null then? I thought the line you marked was the line it was being thrown from (176)? I'm totally confused now.
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
How to resolve a java.lang.NullPointerException
http://www.tmorris.net/pubs/npe/


Tony Morris
Java Q&A (FAQ, Trivia)
Abrahim Daver
Ranch Hand

Joined: Aug 06, 2004
Posts: 69
In If loop, you can put a condition to check whether filename is not null using syntax
[b]
if(FileName != null && FileName.length() > 0)
[b]

This will solve your problem of throwing NullPointer exeception, by not going upto the statement of calculating length on a null object.

Otherwise one can handle Exception in catch block and rethrow it to its calling method/class, where it can be handled.

Abra.
Scott Selikoff
author
Saloon Keeper

Joined: Oct 23, 2005
Posts: 3710
    
    5

Some general advice since you're new to java:

For all public methods that accept objects, always check if input is null before using it. The only time you shouldn't is if you have an explicit contract with the client saying they will never pass you a null value (and even then, they are sometimes wrong).

This includes accessing objects not completely under your control. Unless you know for sure the object has been initialized (such as in a constructor) and it can never be set to null, you should always check it. Null Pointer exceptions are among the most common and meaningless exception since it provides no real indication of the cause of the problem without actually looking at the code. For example, a connection failure is usually meaningful since it gives some indication of why the exception was thrown.

One last tip for these forums, putting "URGENT PLEASE" in the subject doesn't get your question answered any faster, if anything it turns a lot of people off to the topic. We're doing this for fun and we don't need your stress to carry over on to us.


My Blog: Down Home Country Coding with Scott Selikoff
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

"resa,"

Please revise your display name to meet the JavaRanch Naming Policy. To maintain the friendly atmosphere here at the ranch, we like folks to use real (or at least real-looking) names, with a first and a last name.

You can edit your name here.

Thank you for your prompt attention, and enjoy the ranch!

-Marc


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
jiju ka
Ranch Hand

Joined: Oct 12, 2004
Posts: 306
Tony,
Read your article and I agree with it.

In the current application I am working we are avoiding NullPointerException by a different technique. Within the application we are keeping a standard such that every reference should have a valid value. For example
an array reference should atleast be initialized to a zero length array,
A String should be an empty String at the least, etc. Further the standard is insisting that the developer should not do any str == null checks. But in reality we have lot of NullPointerException suppressed or ignored leading to inconsistent application state.

I see this approach in our application as a myth rather than a standard.

Our application is build on top of java sun libraries. As long as java sun libraries are not implementing this standard, our application cannot. Otherwise the developer need to be very accurate in identifying what is Sun provided or not.

What is your opinion on this standard?
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
Jiju - perhaps that question could be asked in a separate thread in intermediate or advanced? As far as we know the original poster here is still trying to understand the basics; let's not distract too much from that.


"I'm not back." - Bill Harding, Twister
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
Originally posted by jiju ka:
Tony,
Read your article and I agree with it.

In the current application I am working we are avoiding NullPointerException by a different technique. Within the application we are keeping a standard such that every reference should have a valid value. For example
an array reference should atleast be initialized to a zero length array,
A String should be an empty String at the least, etc. Further the standard is insisting that the developer should not do any str == null checks. But in reality we have lot of NullPointerException suppressed or ignored leading to inconsistent application state.

I see this approach in our application as a myth rather than a standard.

Our application is build on top of java sun libraries. As long as java sun libraries are not implementing this standard, our application cannot. Otherwise the developer need to be very accurate in identifying what is Sun provided or not.

What is your opinion on this standard?


jiju, I am confident that this approach is flawed - I have tried and failed this way, and many others to no avail. The best way to approach this situation is to acknowledge the basis on which you are attempting to work - in this case, Java itself. As you have discovered, Java contains a language defect, namely, null. Of course, a language defect does not exist without a conflict of requirements, so it is more accurate to say "Java does not meet your requirements". This is why you are attempting to find an optimal workaround.

It is intrinsic to contractual design that some object does not mandate the order of invocation of its operations, otherwise, you would have a functional design. e.g.
class X{Object o;void op1(){o = new Object();}void op2(){o.toString();}}
You cannot mandate the invocation of op1 before op2, since you would no longer have a functional language. I (and some friends) have "toyed" with the idea of using metadata to stipulate valid/invalid orders of invocation for our language specification, but it has since been abandoned due to excessive complexity. So then, the question becomes, what now?

What you can do is either mandate the assignment of fields upon construction to some "null value", such as the empty String, or whatever it is that resembled the concept of null for that given contract type. However, I argue that this simply delays failure, since there are valid use cases where initial assignment of a field can be latent (after construction), and in the event that the field is used before this time, failure may not occur accurately.

Instead, I propose definite assignment semantics for compile-time resolution (which pretty much means that a field cannot be used while in a "constructor" (which has been totally redefined) unless it is definitely assigned). In the event of the use of any field that has not been assigned, and can be resolved at run-time, immediate run-time failure occurs. It is important to distinguish here between "use of" and "dereference of", since it is only the latter case that causes failure in Java. The former case is a superset, and in a Java context, the only bit missing to complete the superset, is the passing of a null reference to a method. For example, in our language, which looks nothing like the following (ick! Java!), this would cause runtime failure:
class X{Object o;void op(){method(o);}}
...upon invocation of the op operation, since an unassigned field is used. The best you can do in Java, is to provide immediate failure upon detection of a null reference to one of these contracts. In fact, you will find in the ContractualJ API Specification that every single contract that accepts one or more reference types will declare to throw NullPointerException if any of these references is null. An exception to this rule has been made in corner cases to allow adaption to the J2SE API Specification. For example, a net.tmorris.adt.sequence.Sequence<String> would not be valid if it were backed by a java.util.List<String>, since the List may contain null elements.

I have just described how null is a (broken) workaround to the inability to mandate order of invocation of operations in a contractual design. I have not described how to avoid assignment of null in a local context. However, I can assert that it is always avoidable, and should always be avoided, without discrimination. To demonstrate this assertion, the ContractualJ API Specification avoids it completely.

I argue that following these rules has massive benefits for both developers and clients, since it is an approach to a formally valid requirement specification - but falls far short due to the restricted context (Java). Therefore, any client who uses the ContractualJ API Specification should notice a clearer and easier method of doing whatever it is that they intend to do. Of course, this API spec. is a one man operation, so it's taking a while.
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
Erm, I just realised that we have digressed in the beginner's forum.
Some other JavaRanch forum or http://forum.contractualj.com/ if you want.
reva oday
Greenhorn

Joined: Dec 18, 2005
Posts: 6
Thanks for all ur advice..

Tony morris site is very usefule to me to understand first of all..
jiju ka
Ranch Hand

Joined: Oct 12, 2004
Posts: 306

perhaps that question could be asked in a separate thread in intermediate or advanced? As far as we know the original poster here is still trying to understand the basics; let's not distract too much from that.


Sorry for that. I took it granted that Tony's site is explanatory enough. Since the original poster is satisfied now, One question to Jim is

The same question about nullPointerException have advanced and basic aspects. Depending on where it is posted (basic, intermediate or advanced) the responders determine the level. Is it agreeable to post the same question in multiple forums? What the user intends is from a set of different solutions which is the best solution.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: how to avoid null pointer exception(URGENT PLEASE)