c# - 捕获异常,然后抛出/发送异常并继续

标签 c# winforms exception try-catch

所以标题可能有点误导,但我想要完成的是读取一组文件,然后将它们组合成一个文件,这就是我现在的位置。

问题是我有一个 catch 寻找异常“FileNotFoundException”,当它被调用时我想继续我的 try 语句(使用“continue”)但让用户知道文件丢失。

我的设置是一个从表单调用的类(它在应该显示错误的表单中)

我考虑过创建一个可以从我的表单注册的事件,但这是正确的方法吗?

    public void MergeClientFiles(string directory)
    {
        // Find all clients
        Array clients = Enum.GetValues(typeof(Clients));

        // Create a new array of files
        string[] files = new string[clients.Length];

        // Combine the clients with the .txt extension
        for (int i = 0; i < clients.Length; i++)
            files[i] = clients.GetValue(i) + ".txt";

        // Merge the files into directory
        using (var output = File.Create(directory))
        {
            foreach (var file in files)
            {
                try
                {
                    using (var input = File.OpenRead(file))
                    {
                        input.CopyTo(output);
                    }
                }
                catch (FileNotFoundException)
                {
                    // Its here I want to send the error to the form
                    continue;
                }
            }
        }
    }

最佳答案

您希望该方法完成其工作并向用户报告问题,对吗? 然后 Oded 提出了正确的建议。稍作修改,代码可能如下所示:

    public List<string> MergeClientFiles( string path )
    {
        // Find all clients
        Array clients = Enum.GetValues( typeof( Clients ) );

        // Create a new array of files
        string[] files = new string[clients.Length];

        // Combine the clients with the .txt extension
        for( int i = 0; i < clients.Length; i++ )
            files[i] = clients.GetValue( i ) + ".txt";
        List<string> errors = new List<string>();

        // Merge the files into AllClientData
        using( var output = File.Create( path ) ) {
            foreach( var file in files ) {
                try {
                    using( var input = File.OpenRead( file ) ) {
                        input.CopyTo( output );
                    }
                }
                catch( FileNotFoundException ) {
                    errors.Add( file );
                }
            }
        }
        return errors;
    }

然后,在调用方中,您只需检查 MergeClientFiles 是否返回非空集合。

关于c# - 捕获异常,然后抛出/发送异常并继续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12554944/

相关文章:

c# - 如何将 DbContext.Database.SqlQuery<TElement>(sql, params) 与存储过程一起使用? EF 代码优先 CTP5

c# - 工具条 WinForms .Net Core 的问题

java - 当发生 SQLException 时如何调用自定义异常?

Java 异常 : New BMP version not implemented yet

c# - 根据属性值映射到类

c# - 即使页面大小设置为更大,目录搜索器对象是否上限为 5000

WinForms 的 iPhone UI 控件

java - 不同类的对象的异常类

c# - 在 UI 线程上创建和启动任务

Winforms RichtextBox 粗体/斜体/下划线格式问题