简体   繁体   中英

How to throw Java SAXParseException for bad XML documents in Try/Catch

I am trying to parse elements out of a XML document. It works for most of them, but sometimes I may get a fatal error because I am given a badly formatted XML document. I want to ignore those cases when I get those XML documents by throwing an exception for it. The console gives me a SAXParseException , but when I call for it in the catch block, it is unable to. I wanted to do it in the JSP scriplet, but it will never be thrown since the scriplet is not actively searching for the SAXException .

I though the solution is to create a method to throw the exception, but again, it says that the SAXParseException will never be thrown in the try / catch statement. What is happening here?

public String parseElementsByTagNameInXML(Document doc, String tagName) throws SAXParseException
        {
            try{
                return doc.getElementsByTagName(tagName).item(0).getTextContent();
        }
        catch(SAXParseException e){
             System.out.println("Failure on Generating MessageID: " + e);
        }

        catch(NullPointerException e){
            //will not spam the console with nullpointexception errors
        }
        catch(Exception e){
            System.out.println("Failure on Generating MessageID: " + e);
        }
            return "";
        }

Your method define that it will throws SAXParseException but your try catch is catching and consuming it without tossing it back up the line. Instead, I think it's printing it out. Try removing that catch and the exception catch, then if it fail by SAXParseException, it'll throw it to whoever call that method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM