How to continue execution after a throw exception in Java?

13.7k views Asked by At

I am reading HTML files from a folder using xml parser that store the clean code in tagNode

try {
    Document doc = new DomSerializer(props, true).createDOM(tagNode);
} catch (Exception ex) {
 ex.printStackTrace();
}

But one of the files is giving me an error :

org.w3c.dom.DOMException: INVALID_CHARACTER_ERR: An invalid or illegal XML character is specified. 

How I can continue running the program after the exception is caught ?


solution #1

    try 
    {
            File folder = new File(path);
            File[] listOfFiles = folder.listFiles();
        FileWriter fstream = new FileWriter("dataset.txt");
            BufferedWriter br= new BufferedWriter(fstream);


for (int i = 0; i < listOfFiles.length; i++) {    
{
        try {
            Document doc = new DomSerializer(props, true).createDOM(tagNode);
        } catch (Exception ex) {
         ex.printStackTrace();
        }
    }
    } catch (Exception ex) {
         ex.printStackTrace();
        }

Given a way around it , why I am getting this error ?

2

There are 2 answers

0
Hunter McMillen On BEST ANSWER

If you are processing a list of files like you mention above you only need the try-catch block that is inside of the for loop:

File folder = new File(path);
File[] listOfFiles = folder.listFiles();
FileWriter fstream = new FileWriter("dataset.txt");
BufferedWriter br= new BufferedWriter(fstream);

for (int i = 0; i < listOfFiles.length; i++)  
{
    try 
    {
       Document doc = new DomSerializer(props, true).createDOM(tagNode);
    } 
      catch (DOMException de) 
      {
         de.printStackTrace();
      }
}
1
Shawn On

Use a try/catch block

try{
   Document doc = new DomSerializer(props, true).createDOM(tagNode);
}
catch(DOMException e){
   //error handling here if you want
}

 //we now hit more code