Home > OS >  Acknowledge and Exception but continue anyway
Acknowledge and Exception but continue anyway

Time:07-16

Simple script where you import a txt file to sum together all the number values. In the txt file there is one letter (incorrectly entered) instead of a number.

StreamReader

12.30 14.30 16.30 17.89 y // Incorrect entry

Using try/catch will ensure that I am aware of this mistake.

enter image description here

As a learning exercise how do I still get the exception comment yet still allow the script to continue. To give an output EVENTHOUGH the final total will be wrong?

enter image description here

CodePudding user response:

to capture the exception message in general (ignoring TryParse etc)

  string message = null;
  try
  {
       // do stuf that might throw
  }
  catch(Exception e)
  {
      message = e.Message;
  }
  if (message != null)
  {
      // error happened and we have the message
  }
  else
  {
       // all ok
  }    
     
  

CodePudding user response:

Since this is for learning, I would recommend using TryParse rather than Parse and rather than placing code in the form, use a class as shown next where return information is done with tuples and deconstruct by the caller.

using System;
using System.Collections.Generic;
using System.IO;

namespace YourNamespace
{
    public class Operations
    {
        public static (decimal total, List<int> linesBad, Exception exception) GetTotals(string fileName)
        {
            List<int> badLines = new();
            decimal total = 0;

            try
            {
                using (StreamReader reader = new(fileName))
                {
                    int index = 0;
                    while (!reader.EndOfStream)
                    {
                        if (decimal.TryParse(reader.ReadLine(), out var result))
                        {
                            total  = result;
                        }
                        else
                        {
                            badLines.Add(index);
                        }

                        index  ;
                    }
                }

                return (total, badLines, null);

            }
            catch (Exception ex)
            {
                return (total, badLines, ex);
            }
        }
    }
}

To keep things simple I use a Console app. Using return values use total for your label, badLines if not empty has any line that was not a decimal and exception if there was a runtime exception e.g. missing file.

static void Main(string[] args)
{
    var (total, badLines, exception) = Operations.GetTotals("example.txt");

    if (exception is null)
    {

        Console.WriteLine($"Total: {total:C2}");

        if (badLines.Any())
        {
            Console.WriteLine($"Bad lines: {string.Join(",", badLines)}");
        }

    }
    else
    {
        Console.WriteLine(exception.Message);
    }

    Console.ReadLine();
}
  •  Tags:  
  • c#
  • Related