Home > Blockchain >  Exception handling in C# with file stream and database
Exception handling in C# with file stream and database

Time:10-22

I have this program, that I have to handle the exceptions for, but I never done it so I'm kind of confused. I'm guessing I'd have to handle exceptions like the value in the textfile is empty, there is no index, there is no "=" or the file is empty, but I don't really know how to define them or where to put them. Here is my code: (the lines in the text file should look like this: EMPIS_MAG_BUDOW=12

EMPIS_DESKA_FASOLKA=2

SM_PORTAL_POL1=-4 )

    using System;
using FirebirdSql.Data.FirebirdClient;
using System.Collections.Generic;
using System.Linq;
using System.IO;

namespace dokselect
{
    class indexstan
    {
        public string index;
        public double standysp;
    }

    class WynikPorownania
    {
        public string Indeks;
        public int Ilosc;
        public override string ToString()
        {
            return Indeks   " : "   Ilosc;

        }

    }
}
    class Program
    {
        public static void Main()
        {
            ///////CONNECTION

            string conn = "database=C:/PCBiznes/BAZA/IXION2_LOGMAG.FB;user=SYSDBA;password=masterkey;DataSource=192.168.24.112;Port=3050";
            FbConnection myConnection = new FbConnection(conn);
            FbDataReader myReader = null;

            string sql = "select KARTOTEKA.indeks, STANMAG.standysp FROM kartoteka JOIN stanmag using(ID_KARTOTEKA);";
            FbCommand myCommand = new FbCommand(sql, myConnection);

            myConnection.Open();
            myReader = myCommand.ExecuteReader();

            ///////LIST lista1
            List<indexstan> listadb = new List<indexstan>();
            double standysp;
            string index;
            while (myReader.Read())
            {
                index = myReader[0].ToString();
                standysp = Convert.ToDouble(myReader[1]);
                listadb.Add(new indexstan { index=index, standysp=standysp });
                //Console.WriteLine(myReader[0].ToString());
            }
            myConnection.Close();
            Console.WriteLine(listadb.Count);


            //RETURN STANDYSP FUNCTION
            double zwr(string myIndex)
            {
                var result = listadb.FirstOrDefault(listadb => listadb.index == myIndex).standysp;
                return result;
            }
            //zwr("EMPIS_DESKA_FASOLKA");

            //READ FROM TXT AND RETURN HIGHER
            string path = "C:/Users/Praktykant/Documents/textdocs/dok1.txt";
            List<WynikPorownania> listatf = File.ReadAllLines(path).Select(line =>
            {
                var linia = line.Split("=");
                string index = linia[0];
                int value = int.Parse(linia[1]);
                return new WynikPorownania {Indeks = index, Ilosc = (int)Math.Max(value, zwr(index))};
            }).ToList();

            //DISPLAY ALL LISTATF CLASSES
            foreach(object WynikPorownania in listatf)
            {
                Console.WriteLine(WynikPorownania);
            }

        }
    }
}

I tried to make an exception like this, if the value is not given but it doesn't work and the program still collapses when the value in the text file is empty

List<WynikPorownania> listatf = File.ReadAllLines(path).Select(line =>
                {
                    var linia = line.Split("=");
                    string index = linia[0];
                    if (linia[1] == "")
                    {
                        throw new Exception("Is empty ... or whatever you caught");
                        return null;
                    }
                    else
                    {
                        int value = int.Parse(linia[1]);
                    }
                

                    return new WynikPorownania { Indeks = index, Ilosc = (int)Math.Max(value, zwr(index)) };
                }).ToList();

CodePudding user response:

To handle exceptions in C# you should use try catch (see c# refence try-catch-finally) In your code I suggest to wrap a try catch around the firebird connection, since you are depending on this:

try {
    // your code
} catch (Exception ex) {
    // define what happens if exception is thrown
}

Its key that you include for instance the firebird connection and the while loop into the try, since those are things your code is depending on.

To handle the value in the text file:

//DISPLAY ALL LISTATF CLASSES
// note that I have replaced the "object" with your class.
foreach(WynikPorownania wynikPorownania in listatf)
{
    if (wynikPorownania.Indeks != ... || wynikPorownania.Ilosc != ... )
        throw new Exception("Is empty ... or whatever you caught");
    Console.WriteLine(wynikPorownania);
}

CodePudding user response:

//try something like below.

class Program
{
    public static void Main()
    {
        //CONNECTION
        try
        {
            //... <YOUR CODE>

           //DISPLAY ALL LISTATF CLASSES
           foreach(object WynikPorownania in listatf)
           {
              Console.WriteLine(WynikPorownania);

              /*if <your condition>
              {
                 throw <your exception1>
              }
              else if <your condition>
              {
                throw <your exception1>
              }*/
           }
        
        }   

        catch (Exception <your Exception>)
        {
            // Throw the message 
            // Or return the code
        }
    }
}
  • Related