Jetnor
Jetnor

Reputation: 531

how to make program call different method if exception was caught

I have a try catch statement which handles reading a list of xml files and outputs them to csv files.

Now I want to be able to move faulty xml files to a different folder from the healthy files but am not sure how to do it.

What I have got so far is as below:

 bool faultyYN = false;
            foreach (string filename in XMLFiles)
            {
                using (var reader = new StreamReader(filename))
                {
                    string shortFileName = Path.GetFileNameWithoutExtension(filename);
                    XMLShredder.DataFile df = null;

                    try
                    {
                        var sw = new Stopwatch();
                        sw.Start();
                        df = Shredder.ShredDocument(XDocument.Load(reader, LoadOptions.SetLineInfo));
                        sw.Stop();
                        var elapsed = sw.ElapsedMilliseconds;
                        _log.InfoFormat(" Shredded file <{0}> in {1}ms", shortFileName, elapsed);
                        string outputFileName = Path.Combine(outputDirectory, shortFileName) + ".csv";

                        sw.Reset();
                        sw.Start();

                        using (var writer = new ChunkedShreddedFileWriter(outputFileName))//full file path
                        {
                            new DataFileCsvWriter().Write(df,
                                                          writer);
                        }
                        sw.Stop();
                        var elapsed2 = sw.ElapsedMilliseconds;
                        _log.InfoFormat(" Wrote file <{0}> in {1}ms", shortFileName, elapsed2);
                    }
                    catch (XmlException e)
                    {
                        _log.Error(String.Format("Reading failed due to incorrect structure in XML Document. File Name : <{0}>. Error Message : {1}.", shortFileName, e.Message), e);
                        faultyYN = true;

                    }
                    catch (IOException e)
                    {
                        _log.Error(String.Format("Reading failed due to IO Exception. File Name : <{0}>. Error Message : {1}.", shortFileName, e.Message), e);
                    }
                if(bool faultyYN == true)
                {
                      MoveFaultyXML(faultyXMLDirectory, shortFileName);

                }

            }
            TidyUp(XMLFiles);//deletes the files after the process has finished.
        }

I have tried adding the Move faulty files to faulty directory after the catch but the files still keep getting deleted.

So basically the method that does not work as I don't know where I should be calling it from is "MoveFaultyXML(faultyXMLDirectory, shortFileName)".

I have read on the net that I shouldn't be using a an exception to branch out but in this case I couldn't think of an alternative solution. The exception has to be thrown for me to know that there is something wrong with the file.

If there is another way of dealing with this which is better practice or if this way works but I am doing it wrong then please help me and I would really appreciate it.

Thanks, Jetnor.

Upvotes: 0

Views: 96

Answers (3)

Daniel Gruszczyk
Daniel Gruszczyk

Reputation: 5612

First solution that comes to my mind would be to:

Move the MoveFaultyXML(faultyXMLDirectory, shortFileName); call to do it within the appropriate catch block:

catch (XmlException e)
{
    //log
    MoveFaultyXML(faultyXMLDirectory, shortFileName); 
}

You don't need the boolean faultyYN.
Now you can create a class representing your XML file (instead of storing just file names in your XMLFiles list):

public class XMLFile
{
    public string FileName { get; set; }
    public bool Delete { get; set; }
}

And set the Delete flag to 'false' if you move the file.
In the TidyUp delete only files with this flag set to 'true'.

An alternative solution would be to:

Replace foreach() with

for(int i=XMLFiles.Count - 1; i >= 0; i--)
{
    string filename = XMLFiles[i];
    //the rest of your code
}

Change the catch block with the XMLException to:

catch (XmlException e)
{
    //log
    MoveFaultyXML(faultyXMLDirectory, shortFileName); 
    XMLFiles.RemoveAt(i);
}

This way when you get to CleanUp function, any files that were moved are no longer on the list to be deleted.

Upvotes: 2

W.K.S
W.K.S

Reputation: 10095

The `XmlException' is thrown when the XML is incorrect, so it is inside this catch block that you have to call your MoveFaultyXML.

Additional Notes:

  1. Don't add YN to boolean names. Use something like xmlIsFaulty = true. This makes the code easier to read because then you have conditional statements like

    if(xmlIsFaulty){MoveFaultyXml();}

which even a non-programmar can understand.

  1. In this code, you're redeclaring the faultyYN variable which should given an error.

    if(bool faultyYN == true) { MoveFaultyXML(faultyXMLDirectory, shortFileName); }

    After you've declared the variable at the start of the method, you do not need to declare it again.

Upvotes: 1

liquidsnake786
liquidsnake786

Reputation: 447

This is because TidyUp(XMLFiles); still gets executed after your exception is caught, you can move TidyUp(XMLFiles); to within the try block or only call it in catch blocks which are needed.

Upvotes: -1

Related Questions