• 0

[Java] How to suppress Fatal Errors in the log


Question

Hi everyone,

I have a Java program that does some XML manipulation. It throws this error in my log:

[Fatal Error] :-1:-1: Premature end of file.

It is not causing any problems and it is beyond my control to fix it. Is there any way I can suppress these errors and clean up my log? Or maybe, change the message to be more friendly?

Thanks for any help. :)

Recommended Posts

  • 0

I believe that I have narrowed it down to here:

public static Document parse(String xml) throws SAXException,IOException {

InputSource source = new InputSource(new StringReader(xml));

DOMParser parser = new DOMParser();

//[Fatal Error] :-1:-1: Premature end of file.

parser.parse(source);

return parser.getDocument();

}

InputSource is from org.xml.sax.InputSource

DOMParser is from org.apache.xerces.parsers.DOMParser

I did not write this code but I currently maintain it and am not sure why the error is being thrown...

  • 0
  Annorax said:
I believe that I have narrowed it down to here:

public static Document parse(String xml) throws SAXException,IOException {

InputSource source = new InputSource(new StringReader(xml));

DOMParser parser = new DOMParser();

//[Fatal Error] :-1:-1: Premature end of file.

parser.parse(source);

return parser.getDocument();

}

InputSource is from org.xml.sax.InputSource

DOMParser is from org.apache.xerces.parsers.DOMParser

I did not write this code but I currently maintain it and am not sure why the error is being thrown...

I haven't done java in a few years but I believe this is where the error is getting thrown. The // bit is a comment of what the error looks like. Try catching the SAXException and IOException then ignoring them or having them return a better message.

Would help more with a bit of code but like I said it's been a long time.

I'm assuming that the problem is with the files that you're trying to open (they're incorrectly terminated) and that they can't be changed.

Edited by monkey13
  • 0
  Annorax said:
I believe that I have narrowed it down to here:

public static Document parse(String xml) throws SAXException,IOException {

InputSource source = new InputSource(new StringReader(xml));

DOMParser parser = new DOMParser();

//[Fatal Error] :-1:-1: Premature end of file.

parser.parse(source);

return parser.getDocument();

}

InputSource is from org.xml.sax.InputSource

DOMParser is from org.apache.xerces.parsers.DOMParser

I did not write this code but I currently maintain it and am not sure why the error is being thrown...

why is the error in your source code?

  • 0

OK a bit of googleing reveals that it is a SAXException so try something like. (will need more work)

public static Document parse(String xml) throws SAXException,IOException {

try{

InputSource source = new InputSource(new StringReader(xml));

DOMParser parser = new DOMParser();

//[Fatal Error] :-1:-1: Premature end of file.

parser.parse(source);

return parser.getDocument();

}

catch (SAXException sxe)

{ // Do what ever you want to do with the exception}

}

}

Syntax and brackets might be a bit off but it's a start for you.

@Ste. The someone has just put the error in as a comment because this bit keeps throwing that error. I think.

  • 0
  JamesCherrill said:
If it's from an Exception, someone has to (1) create it and (2) throw it. That's the code you need to find.

The problem should be in this bit of code. Althought the problem isn't with the code but the fact that the xml files aren't terminated in the manor that the java xml parser likes.

//class constructor sets up for SAXException.

public static Document parse(String xml) throws SAXException ,IOException{

//Create objects and get xml

InputSource source = new InputSource(new StringReader(xml));

DOMParser parser = new DOMParser();

//[Fatal Error] :-1:-1: Premature end of file.

//Parse xml file. SAXException thrown here due to incorrect/missing xml end of file.

parser.parse(source);

return parser.getDocument();

}

Although another way to fix it might be to append the xml that is passed to the string reader with the correct end of file token.

No need for try and catch then.

Also how is the xml that is passed to this class loaded in? It could be that the EOF token is getting chopped off then. That would mean that the files are ok and the code is introducing the error.

  • 0

Maybe if you can find the ACTUAL CODE where the Exception is created and thrown then you could see the exact conditions under which that happens, and maybe that will enable you either to identify a work-around or sub-class the offending code to override that behaviour. The code fragment you keep on posting is NOT the code we need to look at.

  • 0
  JamesCherrill said:
Maybe if you can find the ACTUAL CODE where the Exception is created and thrown then you could see the exact conditions under which that happens, and maybe that will enable you either to identify a work-around or sub-class the offending code to override that behaviour. The code fragment you keep on posting is NOT the code we need to look at.

I'll assume you are talking to me.

1. It's not my code fragment it's Annorax's

2. You obviously don't understand how JAVA works. Quick lesson for you,

This is the class constructor

public static Document parse(String xml) throws SAXException ,IOException{

The bit I've bolded means this class can throw these exceptions.

parser.parse(source);

This line throws the exception. When the xml parser InputSource tries to parse the xml given to it it doesn't like the way the xml ends. So it throws the SAXException.

The throw statement is within the code of the InputSource. Since this is part of the JAVA platform source you wouldn't go in and change that.

End of JAVA lesson.

Edit:

  JamesCherrill said:

Probably irrelevent. This is for the same error if you pass your xml object through the parser twice. Unless the xml string is passed through the parser somewhere else in the code before it gets here that's not the cause.

  • 0

Thank you all for trying to help me.

Yes, the comment with the error is right above where the error is thrown i.e. "parser.parse(source);" throws the error. This is not an object I have access to as it's in xercesImpl.jar.

The try/catch is a good idea and one I thought of. When I implement it as follows:

InputSource source = new InputSource(new StringReader(xml));

DOMParser parser = new DOMParser();

try {

parser.parse(source);

} catch (Exception e) {

System.out.println("Fatalr");

}

return parser.getDocument();

I get something like this in my log:

Fatal error

[Fatal Error] :-1:-1: Premature end of file.

Fatal error

[Fatal Error] :-1:-1: Premature end of file.

Fatal error

[Fatal Error] :-1:-1: Premature end of file.

So the "Premature end of file" error is thrown from within a class that I cannot edit.

  • 0

Try catch (SAXException sxe) instead of catch(Exception e)

Although from the link JamesCherrill posted

http://dschneller.blogspot.com/2008/01/sax...ure-end-of.html

If you parse something twice you will get an error. Is the xml parsed anywhere else in the code? If it is this is a really stupid way of doing it. Parse once then manipulate many.

The way this Daniel Schneller does it on his blog is stupid. He parses the whole thing once then looks at the type then parses the whole thing again. What a waste of time. Parse once, store, then manipulate based on the type.

  • 0

monkey13:

Not sure what you're smoking - are you always so aggressive?

Anyway, in the name of accuracy...

public static Document parse(.. is NOT a "class constructor"

Constructors are of the form .... ClassName(params...) { ...

I didn't suggest changing the Java platform source, I suggested possibly subclassing it.

Have a nice day

J

  • 0
  JamesCherrill said:
monkey13:

Not sure what you're smoking - are you always so aggressive?

Anyway, in the name of accuracy...

public static Document parse(.. is NOT a "class constructor"

Constructors are of the form .... ClassName(params...) { ...

You started mouthing of about

  JamesCherrill said:
Maybe if you can find the ACTUAL CODE .... The code fragment you keep on posting is NOT the code we need to look at.

Considering I take caps to mean shouting your the one who started getting aggressive.

Time for another JAVA lesson.

public static Document parse(String xml) throws SAXException ,IOException{

Is the constructor for this class. If not where is the constructor then? How else is the class instantiated?

Lets take the basic example from the JAVA tutorial

  Quote
A class contains constructors that are invoked to create objects from the class blueprint. Constructor declarations look like method declarations?except that they use the name of the class and have no return type. For example, Bicycle has one constructor:

public Bicycle(int startCadence, int startSpeed, int startGear) {

gear = startGear;

cadence = startCadence;

speed = startSpeed;

}

To create a new Bicycle object called myBike, a constructor is called by the new operator:

Bicycle myBike = new Bicycle(30, 0, 8);

now the line could read public static Bicycle(int startCadence, int startSpeed, int startGear) throws SAXException ,IOException

It will still be the constructor. I call it the class constructor because is is also the definition of the class. Ok that my not be technically correct in some people's eyes but it's how I was taught. It is however definitely a constructor.

End of JAVA lesson.

  • 0

OK, I'm not a Java guy, as James well knows, but a static method cannot be a constructor.

public [b]static[/b] Document parse(String xml) throws SAXException ,IOException{
///...

It's a static method called parse, not a constructor.

Anyhoo, relax everyone. It's just code! :)

  • 0
  azcodemonkey said:
OK, I'm not a Java guy, as James well knows, but a static method cannot be a constructor.

Technically yes it is. You just don't instantiate it in the same way as a non static class. You don't need to because JAVA handles it all behind the scenes. With a non-static method you would have to do Bicycle myBike = new Bicycle(30, 0, 8); With a static method you can't instantiate an object of this class with a lifetime. ie. the object only exists for as long as the static method is running.

Think of it like this. When you use .parse(xml) what it actually does is creates an object (with the constructor) that you can not access performs the parse() function and then deletes the object.

Back on track to helping Annorax now.

Annorax use catch (SAXException sxe) I've remembered that this kind of exception is actually an "Exception e" and a "String message" (SAXException(String message, Exception e)). So in your earlier test just catching "Exception e" and not "String message" gave two errors. One that you created from catching the "Exception e" and the second from the "String message" part of SAXException you didn't catch.

  • 0

Annorax: I don't think there's anything more I can do in this thread except, in the politest possible way, recommend that you get a second opinion on what monkey13 is writing. You can PM me if you'd like any help.

Roger and Out.

J

  • 0

Annorax. I can only suggest in the politest possible way that if you want to get a second opinion you don't pm JamesCherill. If you want a second opinion I'd ask someone who knows about JAVA. He hasn't actually offered any help, apart from, sub class a method from the JAVA package, to get round your error. Which IMHO is bad practice. If some code is so bad that you have to change the JAVA platform to get it to work I would scrap/change that bit of code.

@JamesCherill If you have any ideas or help why not post them here? They may help someone else latter. Any discussion we have had about the semantics of JAVA does not change the fact that you have offered zero good practice solutions to the problem. Hell you don't even think the problem can be solved in the bit of code posted (and you couldn't identify that the exception was being created and thrown there). No you're probably right. It'd be better to rewrite the JAVA package. :no:

Edited by monkey13
  • 0

Hi!

This output is printed by DefaultErrorHandler from inside of xerces staff.

To suppress this you should provide your own handler implementation.

Just implement XMLErrorHandler interface and provide implementation as a parameter to your parser:

	parser.setProperty(
		"http://apache.org/xml/properties/internal/error-handler", 
		 new MyXMLErrorHandler())

It should help.

  • 0

Old, I know, but I had to comment ....

  monkey13 said:
Technically yes it is. You just don't instantiate it in the same way as a non static class. You don't need to because JAVA handles it all behind the scenes.

Have you got reference for your above statement?

  Quote
With a non-static method you would have to do Bicycle myBike = new Bicycle(30, 0, 8); With a static method you can't instantiate an object of this class with a lifetime.

actually an object can have a static method as well as variables which can be called upon. A static method can instigate it's self, take the singleton pattern.

  Quote
ie. the object only exists for as long as the static method is running.

again, this is not what I understand, so I'm interested in some references.

  Quote
Think of it like this. When you use .parse(xml) what it actually does is creates an object (with the constructor) that you can not access performs the parse() function and then deletes the object.

Again, constructors are called to create objects and I dont think calling a static method will instigate or call the constructor of the class.

Even if a call to a static method instigates an object behind the scenes (waiting on reference), I really doubt the JVM will delete the object as that defeats the purpose of statics.... you would lose your static variable values if you had them....

you can call static methods and access static variables on an object.

  • 0

Hi _kane81. I'll try and clear up your questions but as I said earlier it's been a while since I used Java.

  _kane81 said:
Have you got reference for your above statement?

Not sure if I can find a direct reference (I'll keep looking) but if you think about it then that must be how it works. If you have a static class (or a class, that you have not instantiated, with a static method) it would be possible to code in Java without it being object orientated. If Java didn't do this behind the scenes.

  _kane81 said:
actually an object can have a static method as well as variables which can be called upon. A static method can instigate it's self, take the singleton pattern.

Whoops re-reading I meant class instead if method. What you're saying about methods within a non-static class is right.

  _kane81 said:
again, this is not what I understand, so I'm interested in some references.

See above. I know it's a bit of a cop out but if you have not instantiated a non-static class and use a static method within it Java must create an object of that class to use the static method.

  _kane81 said:
Again, constructors are called to create objects and I dont think calling a static method will instigate or call the constructor of the class.

Even if a call to a static method instigates an object behind the scenes (waiting on reference),

I've been thinking about this one more. If you call a static method of a non-static class you have not instantiated it must construct an object of it somehow. I may retract this statement because I don't know and can't find exactly how it does it. It may not call the constructor there might be a special set of rules for this.

Also I've just found this Static/Class methods. I know it's not a direct answer as to how Java does the creating, handling and destruction of static classes and methods but if you can come up with a way that this line (double avgAtt = MyUtils.mean(attendance)) is executed without the creation of some kind of object I'll be very interested.

  _kane81 said:
I really doubt the JVM will delete the object as that defeats the purpose of statics.... you would lose your static variable values if you had them....

Yes you're right for static classes. It would be daft to delete them. As for static variables I'm not sure how they are handled as they are constant for all objects of a class (or programme depending on how you declare them). With regard to a not instantiated class with a static method I suppose it must either create one object and reuse it if you call the same way again or create then delete. Otherwise there might be a load of objects building up.

  • 0

I think you're confusing "classes" for "objects", and statics belong to the class, not an instance of a class. The class loader initializes a class when a static member is invoked, assigned or accessed. Classes are unloaded when the execution of the program ends, with some exceptions.

http://java.sun.com/docs/books/jls/third_e.../execution.html

My guess is that Class members, a.k.a. statics, are put on the stack and not on the heap, but I have yet to see any documentation that says one way or the other. It could be totally VM dependent.

  Quote
If you have a static class (or a class, that you have not instantiated, with a static method) it would be possible to code in Java without it being object orientated. If Java didn't do this behind the scenes.

It is possible to code in Java without using objects.

  Quote
I've been thinking about this one more. If you call a static method of a non-static class you have not instantiated it must construct an object of it somehow. I may retract this statement because I don't know and can't find exactly how it does it. It may not call the constructor there might be a special set of rules for this.

It doesn't call any constructor. Class initialization is not equal to class construction.

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Last chance to claim VideoProc Converter AI v7.5 ($78.90 Value) for free by Steven Parker Claim your free license (worth $78.90) today, before the offer expires today, June 18. Equipped with AI tools for video and image enhancement, smoothness, and stabilization. Remaster low-quality videos and photos, convert, edit, compress, download, and record with GPU acceleration! Key Features of VideoProc Converter AI V7.5: AI Video Upscaling: Upscale low-res, old, grainy videos/DVDs/recordings by 400% to HD/4K for stunning visuals on larger screens. AI Image Enhancement: Upscale images and AI art to 8K/10K for better cropping, editing, printing, and sharing. AI Stabilization: Intelligently stabilize shaky GoPro/drone/camera footage with controllable cropping ratios. AI Frame Interpolation: Boost FPS from 30/60 to silky-smooth 120/240/480, or create epic slow-motion effects. 5-in-1 Video Toolkit: Convert, edit, compress, download, and record with the highest possible quality. GPU Acceleration: Expedite video processing, even on older computers. How to get it Please ensure you read the terms and conditions to claim this offer. Complete and verifiable information is required in order to receive this free offer. If you have previously made use of these free offers, you will not need to re-register. While supplies last! Download VideoProc Converter AI V7.5 ($78.90 Value, now FREE) Offered by Digiarty, view other free resources The below offers are also available for free in exchange for your (work) email: Continuous Testing, Quality, Security, and Feedback ($27.99 Value) FREE – Expires 6/18 VideoProc Converter AI v7.5 for FREE (worth $78.90) – Expires 6/18 Macxvideo AI ($39.95 Value) Free for a Limited Time – Expires 6/22 Microsoft 365 Copilot At Work ($60 Value) FREE – Expires 6/25 Natural Language Processing with Python ($39.99 Value) FREE – Expires 6/25 Excel Quick and Easy ($12 Value) FREE – Expires 6/24 The Inclusion Equation: Leveraging Data & AI ($21 Value) FREE – Expires 6/24 The Ultimate Linux Newbie Guide – Featured Free content Python Notes for Professionals – Featured Free content Learn Linux in 5 Days – Featured Free content Quick Reference Guide for Cybersecurity – Featured Free content We post these because we earn commission on each lead so as not to rely solely on advertising, which many of our readers block. It all helps toward paying staff reporters, servers and hosting costs. Other ways to support Neowin The above deal not doing it for you, but still want to help? Check out the links below. Check out our partner software in the Neowin Store Buy a T-shirt at Neowin's Threadsquad Subscribe to Neowin - for $14 a year, or $28 a year for an ad-free experience Disclosure: An account at Neowin Deals is required to participate in any deals powered by our affiliate, StackCommerce. For a full description of StackCommerce's privacy guidelines, go here. Neowin benefits from shared revenue of each sale made through the branded deals site.
    • They pulled this same crap with Google Workspace. "hey you get AI now so we are raising your prices". I disabled it for my org but we still have to pay. F this stupid 1984 tiny hat spy crap.
    • Samsung could unveil its Galaxy XR headset ‘Project Moohan' in September by Sagar Naresh Bhavsar Next month, Samsung is expected to unveil the Galaxy Z Fold7, the Galaxy Z Flip7, and an affordable Galaxy Z Flip7 FE, along with the Galaxy Watch8 series. However, the launches don't end there. A fresh report out of South Korea hints that Samsung could launch its much-awaited Galaxy XR augmented reality headset in September. The company has codenamed its first XR headset as "Project Moohan," which translates to "Project Infinite." Samsung has already showcased the Galaxy XR headset a few times in the past. In fact, popular tech YouTuber Marques Brownlee - also known as MKBHD -, got his hands on the Galaxy XR and revealed interesting details about the upcoming device. The Galaxy XR is rumored to come with a sharper display compared to the Apple Vision Pro and run on Google's new operating system for AR and VR headsets, the Android XR. Fast forward to now, Korean publication Newspim reports that Samsung is ready to launch the Galaxy XR headset on September 29 in its home country. Notably, the headset will be unveiled at an Unpacked event and later will go on sale on October 13. Globally, the Galaxy XR headset is expected to launch soon afterwards, though any specific date isn't mentioned. Additionally, the report suggests that fans can expect more teaser videos and prototypes of the headset at the upcoming Unpacked event for the Galaxy Z Fold7 and Flip7. The report also spills some details about the specifications of the Galaxy XR headset. Under the hood, it could run on Qualcomm's new XR2+ Gen 2 chip, made using Samsung's 4nm process. Samsung is also expected to introduce tight integration with its Galaxy ecosystem to offer a connected experience. It will be interesting to see how Samsung holds up against the likes of Meta, which already dominates the XR market, while Apple struggles with high Vision Pro prices.
    • I've put it behind a login for the time being.  I had something like 600,000 requests from just from Alibaba IP addresses that didn't clarify they were bots or scrapers, and so not easy to block using user agent filtering.  I didn't have any issues with bandwidth or accessibility, but that's 600,000 requests just from one cloud provider made to my spinning rust hard drives, that I have to personally pay for when they die, by bots being ran by corrupt mega corporations ignoring my polite requests that they not scrape me and that the information only be accessed by real humans. If any of y'all here were actually using my Kiwix mirror, I have no issue whatsoever creating a username and password for you, just hit me up using one of the methods listed on my personal site and I'll make one for you. https://marcusadams.me
    • I always turn encryption off 1st boot, crazy its on by default on new computers, it should ASK you ON or OFF on 1st boot,, So many people dont even know its on , then forget their windows login and microsoft account,, RETarDED Microsoft is now, , i also find having it on slows things down too
  • Recent Achievements

    • Week One Done
      vivetool earned a badge
      Week One Done
    • Reacting Well
      pnajbar earned a badge
      Reacting Well
    • Week One Done
      TBithoney earned a badge
      Week One Done
    • First Post
      xuxlix earned a badge
      First Post
    • First Post
      Tomek Święcicki earned a badge
      First Post
  • Popular Contributors

    1. 1
      +primortal
      672
    2. 2
      ATLien_0
      288
    3. 3
      Michael Scrip
      223
    4. 4
      +FloatingFatMan
      195
    5. 5
      Steven P.
      143
  • Tell a friend

    Love Neowin? Tell a friend!