【问题标题】:Exception handling in C# with file stream and database使用文件流和数据库在 C# 中处理异常
【发布时间】:2021-12-07 22:38:29
【问题描述】:

我有这个程序,我必须处理它的异常,但我从来没有做过,所以我有点困惑。我猜我必须处理异常,例如文本文件中的值为空,没有索引,没有“=”或文件为空,但我真的不知道如何定义它们或在哪里把它们。这是我的代码: (文本文件中的行应如下所示: 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);
            }

        }
    }
}

我尝试过这样的异常,如果没有给出值但它不起作用并且当文本文件中的值为空时程序仍然崩溃

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();

【问题讨论】:

  • 不要使用异常处理程序来解决您所描述的“非异常”情况。编写代码来处理这些情况并将信息添加到日志文件中。在此代码中添加异常处理程序将导致编写不佳的代码,难以让它继续读取有错误的行之后的行。

标签: c# exception error-handling stream database-connection


【解决方案1】:

要在 C# 中处理异常,您应该使用 try catch(请参阅 c# refence try-catch-finally) 在您的代码中,我建议在 firebird 连接周围包装一个 try catch,因为您依赖于此:

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

你在 try 中包含例如 firebird 连接和 while 循环的关键,因为这些是你的代码所依赖的东西。

处理文本文件中的值:

//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);
}

【讨论】:

  • 我认为这个异常必须在列表函数中处理,因为这是它从文件中获取数据的地方,如果索引没有赋值(fe.“EMPIS_DESKA_FASOLKA=”)程序崩溃。我不知道代码到底应该放在哪里......
【解决方案2】:

//试试下面的方法。

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
        }
    }
}

【讨论】:

  • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-01-30
  • 2010-09-28
  • 1970-01-01
  • 1970-01-01
  • 2018-02-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多