如何在 C# 控制台应用程序中以正确的方式处理异常

How to handle exception the right way in c# console app

我有一个小型控制台应用程序,它将安排在一天中的不同时间间隔,此控制台应用程序将从 ftp 下载文件。 我有一个名为 BatchProcessor 的 class,它从 ftp 下载文件,根据供应商类型解压缩它们,将它们放入不同的供应商文件夹中,然后读取并存储到 SQL 服务器中数据库。

我需要一些建议来判断我所做的是对还是错,因为我几乎需要在任何阶段捕获异常....

这是代码框架Program.cs

 class Program
    {
        static void Main(string[] args)
        {
var batchProcessor = new BatchProcessor();
            batchProcessor.Start();
        }
    }

这是 BatchProcessor class

public class BatchProcessor
{
    public bool Start()
    {
        try
        {
            var result = Connect();
            if (!result) return false;

            result = SearchLatestFiles();
            if (!result) return false;

            result = DownloadFiles();
            if (!result) return false;
        }
        catch (Exception)
        {

            throw;
        }

    }

    public bool Connect()
    {
        try
        {
            // 1. Connect to FTP
        }
        catch (Exception)
        {
            throw;
        }

    }

    public bool SearchLatestFiles()
    {
        try
        {
            // 1. Look for the latest fils
        }
        catch (Exception)
        {

            throw;
        }

    }

    public bool DownloadFiles()
    {
        try
        {
            // 1. Latest files found so download them.
        }
        catch (Exception)
        {

            throw;
        }

    }
}

由于应用程序将 运行 无人值守,诊断错误的最佳方法是部署某种日志记录。我建议使用作为 Nuget 包提供的 log4net。它很容易安装和配置,在抛出错误之前,您应该记录错误消息和堆栈。 每天查看这些日志的良好做法。 还有一件事:你在你的 class 中抛出咳嗽错误,但 main 不处理这些错误 - 它会导致应用程序崩溃和异常终止。

祝你好运