JulioBordeaux
JulioBordeaux

Reputation: 504

How to determine that no exceptions have been caught java

I have a code for my xml file validation:

try {
        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        domFactory.setValidating(true);
        DocumentBuilder builder = domFactory.newDocumentBuilder();
        builder.setErrorHandler(new ErrorHandler() {

            public void error(SAXParseException exception) throws SAXException {
                System.out.println("Error: " + exception.getMessage());
            }
            public void fatalError(SAXParseException exception) throws SAXException {
                System.out.println("Fatal error: " + exception.getMessage());
            }

            public void warning(SAXParseException exception) throws SAXException {
                System.out.println("Warning: " + exception.getMessage());
            }
        });

            Document doc = builder.parse(xml);
        } catch (SAXException e) {
            e.printStackTrace();

        } catch (IOException e) {
            e.printStackTrace();

        } catch (ParserConfigurationException e) {
            e.printStackTrace();

        } 

I can't figure out how should I organize my exception handling, so I could print message "File is valid!" like this System.out.println(xml + " is valid!"); or similarly.

Upvotes: 0

Views: 81

Answers (4)

JulioBordeaux
JulioBordeaux

Reputation: 504

I managed to solve my problem. I simply had to add throw exception; lines to my ErrorHandler methods so I could track a validation process.

Upvotes: 0

Roman C
Roman C

Reputation: 1

You should check the javadoc for parse method. it would return null if any exception occurred. Then you can check for doc == null next after the try/catch block or in the finally block.

Upvotes: 0

user1907906
user1907906

Reputation:

If this line

Document doc = builder.parse(xml);

did not throw an exception, parsing worked. Do what you want after this line.

The bodies of the methods of the ErrorHandler should perhaps not only print output and continue. An error of fatal error should stop parsing.

Upvotes: 2

Balduz
Balduz

Reputation: 3570

Just add that line right before you start the catch clauses. If it gets to there, it means that no exceptions have been raised.

Upvotes: 1

Related Questions