Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / August 2007

Tip: Looking for answers? Try searching our database.

NullPointerException handling

Thread view: 
ramu - 17 Aug 2007 00:18 GMT
i,
     I have the following code.

package transform;

import oracle.xml.schemavalidator.XSDValidator;
import oracle.xml.parser.schema.XSDException;
import oracle.xml.parser.schema.XMLSchema;
import oracle.xml.parser.schema.XSDBuilder;
import oracle.xml.parser.v2.XMLError;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;
import java.net.URL;

public class SchemaValidator{

       public void validateSchema(String SchemaUrl, String
XmlDocumentUrl)
       {
               try {
                       XSDValidator xsdValidator=new XSDValidator();
                       XSDBuilder builder = new XSDBuilder();
                       URL    url =  new URL(SchemaUrl);
                       XMLSchema schemadoc =
(XMLSchema)builder.build(url);
                       xsdValidator.setSchema(schemadoc);

                       Validator handler=new Validator();
                       XMLError xmlError=new XMLError();
                       xmlError.setErrorHandler(handler);
                       xsdValidator.setError(xmlError);
                       xsdValidator.validate(new
URL(XmlDocumentUrl));
                       if(handler.validationError==true)
                               System.out.println("This XML Document
has Error: " + handler.saxParseException.getMessage());
                       else
                               System.out.println("This XML Document
is valid");

               }catch(java.lang.NullPointerException npe)
                {
                       System.out.println("NullPointerException
"+npe.getMessage());
                }
               catch(java.io.IOException ioe)
               {
                       System.out.println("IOException
"+ioe.getMessage());
               }catch (SAXException e) {
                       System.out.println("SAXException
"+e.getMessage());
               }
               catch (XSDException e) {
                       System.out.println("SAXException
"+e.getMessage());
               }
       }

       private class Validator extends DefaultHandler{

               public boolean  validationError = false;
               public SAXParseException saxParseException=null;
               alidationError = true;
               saxParseException=exception;
               }

               public void fatalError(SAXParseException exception)
throws SAXException{
           validationError = true;
           saxParseException=exception;
               }
               public void warning(SAXParseException exception)
throws SAXException{}

          }

       public static void main(String[] argv){
               try{
               String SchemaUrl=argv[0];
               String XmlDocumentUrl=argv[1];
               SchemaValidator validator=new SchemaValidator();

               validator.validateSchema(SchemaUrl, XmlDocumentUrl);

                       } catch(java.lang.NullPointerException npe)
                       {

System.out.println("NullPointerException");
                       }
       }

Here XmlDocumentUrl is the xml document. Am trying to validating a xml
document(XmlDocumentUrl) with the schema specified by SchemaUrl. But
when I miss some attribute in the xml document(XmlDocumentUrl) its
throwing NullPointerException. After catching the NullPointerException
I want to handle it. I want to print an error message which specifies
in which file(XmlDocumentUrl) it occured and the line in that
file(XmlDocumentUrl). Can anyone tell me how to do this?
Manish Pandit - 17 Aug 2007 00:27 GMT
> i,
>       I have the following code.
[quoted text clipped - 96 lines]
> in which file(XmlDocumentUrl) it occured and the line in that
> file(XmlDocumentUrl). Can anyone tell me how to do this?

Yes. It is called a Stack Trace.

npe.printStackTrace();

-cheers,
Manish
Manish Pandit - 17 Aug 2007 00:34 GMT
> > i,
> >       I have the following code.
[quoted text clipped - 105 lines]
>
> - Show quoted text -

Oops..sorry! I thought you wanted to show the line number where
exception occured.

You should not catch NPEs - they normally indicated uninitialized
references, or something wrong with the flow. Something in the arglist
is null, or the object you're calling the method on is null. This is
something you debug, not catch.

The exception should spew out a trace on the console (when not
catched) - follow the trace and see what could be the problem.

-cheers,
Manish
ramu - 17 Aug 2007 21:29 GMT
Hi,
   The intention here is to tell the user, that he has not specified
any attribute(NULL value) in the XML document So I have to tell the
user in which line he is missing the attribute in the input XML
document.  Any idea how to do this?

Regards
Oliver Wong - 17 Aug 2007 23:53 GMT
> i,
>      I have the following code.

[snip code]

[...]
> Am trying to validating a xml
> document(XmlDocumentUrl) with the schema specified by SchemaUrl. But
[quoted text clipped - 3 lines]
> in which file(XmlDocumentUrl) it occured and the line in that
> file(XmlDocumentUrl). Can anyone tell me how to do this?

   Catch the NPE, wrap it in a new exception of your own design (e.g.
MissingAttributeException) and throw that.

   Catch the MissingAttributeException within the method which knows the
name of the file. Display the error at that point.

   - Oliver
Manivannan Palanichamy - 18 Aug 2007 07:00 GMT
> i,
>       I have the following code.
[quoted text clipped - 96 lines]
> in which file(XmlDocumentUrl) it occured and the line in that
> file(XmlDocumentUrl). Can anyone tell me how to do this?

Why dont you add an if condition to check null values?
like,
if (xsdValidator == null)
  throw new RuntimeException("xsdValidator is null.");

NullPointerExcetpion is something, an application is not supposed to
throw. Remember, every NullPointerException is considered to be a Bug
by many design principles. Applications should add null handles (like
if condition) and wrap it by a custom exception & then throw.

--
Manivannan Palanichamy
http://mani.gw.googlepages.com/index.html
Ben Phillips - 18 Aug 2007 13:06 GMT
> if (xsdValidator == null)
>    throw new RuntimeException("xsdValidator is null.");

Eh. Wrapping a specific subtype of RuntimeException in a plain vanilla
RuntimeException? Another one for the WTF file...

If it shouldn't ever be null, leave the exception alone. If it could be
null due to invalid user input, the user input needs validating so that
the null never travels deeper than the UI layer. If it could be null for
other reasons, it should be transformed into a checked exception (e.g.
into IOException if nulls sometimes result from a particular species of
network protocol barf) or handled on-site (e.g. as a special-case
allowed parameter value to your method).
Karl Uppiano - 18 Aug 2007 19:07 GMT
>> if (xsdValidator == null)
>>    throw new RuntimeException("xsdValidator is null.");
>
> Eh. Wrapping a specific subtype of RuntimeException in a plain vanilla
> RuntimeException? Another one for the WTF file...

I would at least re-throw it wrapped in an IllegalArgumentException. That
would tell the user it was something *they* did wrong.

[snip]
Greg R. Broderick - 18 Aug 2007 22:02 GMT
ramu <ramu.ask@gmail.com> wrote in news:1187306323.821067.319820
@g4g2000hsf.googlegroups.com:

> when I miss some attribute in the xml document(XmlDocumentUrl) its
> throwing NullPointerException. After catching the NullPointerException
> I want to handle it. I want to print an error message which specifies
> in which file(XmlDocumentUrl) it occured and the line in that
> file(XmlDocumentUrl). Can anyone tell me how to do this?

The parser (whether it is your code or the underlying XML processing /
parsing code) should not be throwing a NullPointerException in this case,
but should rather be throwing an exception that is more directly related to
the cause of the exception (e.g. SAXException, DOMException).  A
NullPointerException is not suitable for the purposes that you are trying
to put it, as it is far to general of an exception (it could have a very
wide range of causes, only one of which would be a missing XML attribute).  

I would track down the actual line of code that is throwing this exception
and:

1.  if this is your code, fix it so that the missing attribute results in a
more appropriate thrown exception.

2.  if this is in the underlying code that you are calling, work around it
(feed the underlying code different input parameters, or implement the
SAXErrorHandler interface in your code) so that the NullPointerException
isn't thrown.

3.  if you cannot do #2 and the NullPointerException is thrown by the
underlying code, then get a different XML parser/validator instead of the
one that you're presently using.

Signature

---------------------------------------------------------------------
Greg R. Broderick                  usenet200705@blackholio.dyndns.org

A. Top posters.
Q. What is the most annoying thing on Usenet?
---------------------------------------------------------------------

Ben Phillips - 19 Aug 2007 01:07 GMT
> 3.  if you cannot do #2 and the NullPointerException is thrown by the
> underlying code, then get a different XML parser/validator instead of the
> one that you're presently using.

There's also "transform the exception". Wrap it in SAXException or
whatever. (I'm fairly sure I suggested something similar before, using
an example where IOException was the appropriate checked exception type.)
Greg R. Broderick - 19 Aug 2007 04:27 GMT
Ben Phillips <b.phillips@a5723mailhost.net> wrote in news:fa81kn$q90$1
@aioe.org:

>> 3.  if you cannot do #2 and the NullPointerException is thrown by the
>> underlying code, then get a different XML parser/validator instead of the
[quoted text clipped - 3 lines]
> whatever. (I'm fairly sure I suggested something similar before, using
> an example where IOException was the appropriate checked exception type.)

Transforming the exception is fatally flawed -- the NullPointerException can
happen for any number of reasons (one of which might be this missing
attribute).  Interpreting every possible NPE as caused by a missing attribute
is erroneous, and is likely to cause more problems than it solves.  It would
be analogous to a medical doctor interpreting every instance of a headache as
caused by a brain tumor.

Moreover, other, more specific exception types (like SAXParseException) carry
'interesting' information about the location of the error within the XML
document.  NullPointerExceptions don't carry this same level of specific
information.

Cheers!

Signature

---------------------------------------------------------------------
Greg R. Broderick                  usenet200707@blackholio.dyndns.org

A. Top posters.
Q. What is the most annoying thing on Usenet?
---------------------------------------------------------------------

Ben Phillips - 19 Aug 2007 09:52 GMT
Well if possible you want to catch the null itself before it causes NPE,
and transform it.

If the NPE comes from code you call, but don't control, you might have
to resort to transforming it. In that case you'd want to debug all NPEs
of other causes until there were none first. Or if you can catch the
NPE, evaluate some expression that is true only if the NPE was caused in
a particular way, transform it if so, and rethrow it unaltered otherwise.

Most likely though if you're using a library that throws NPEs when it
should throw some checked exception instead, then you ought to report it
to the library's makers as a bug. Still, until they fix it you may need
to work around it. It's up to you to weigh your various options there,
but often you won't want it to bring your Big Important Server(tm) or
whatever to a screeching halt every time it happens.


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.