【问题标题】:C# Ignoring ExceptionC# 忽略异常
【发布时间】:2018-08-07 08:13:53
【问题描述】:

我有一个调用“刷新”方法的按钮,当单击该按钮而不选择另一个按钮的路径时,我的方法会调用异常。我怎么能忽略这个异常而不做任何事情?我知道我可以忽略这样的异常:

 try
  {
   blah
  }
 catch (Exception e)
  {
   <nothing here>
  }

我的情况是这样的:

void refresh() //gets called by button
        {
            listBox1.Items.Clear();

            //will cause exception
            var files = System.IO.Directory.GetFiles(objDialog.SelectedPath, "*.*", System.IO.SearchOption.AllDirectories);

            foreach (string file in files)
            {
               xxx
            }
            xxx
            xxx
        }

线

var files = System.IO.Directory.GetFiles(objDialog.SelectedPath, "*.*", System.IO.SearchOption.AllDirectories);

引发无效路径异常。如果我将代码放入 try-catch,

files

在foreach (string file in files) 中找不到更多代码。

我做错了什么?

【问题讨论】:

  • 将代码-bnlock 留空? catch { }.However 你应该只在极少数情况下这样做,吞咽异常被认为是一件非常糟糕的事情。但是我怀疑 InvalidPathException 是否应该被吞掉。而是尝试通过检查文件是否存在来避免该异常。
  • 并不是说你可以用 files 做任何事情。
  • 程序打开一个文件夹,通过单击单选框,您可以过滤特定文件。当用户在选择文件夹之前进行过滤(这不是一件坏事)时,会弹出异常。每次用户更新过滤器以更新列表框时,我都需要使用此方法。

标签: c# exception try-catch


【解决方案1】:

您不应该吞下异常。它们通常包含有关究竟出了什么问题的信息。除了以非常奇怪的方式处理异常,您应该首先通过检查目录是否存在来避免它:

void refresh() //gets called by button
{
    listBox1.Items.Clear();
    if(!String.IsNullOrEmpty(objDialog.SelectedPath) && Directory.Exists(objDialog.SelectedPath))
    {
        var files = System.IO.Directory.GetFiles(objDialog.SelectedPath, "*.*", System.IO.SearchOption.AllDirectories);
        foreach (string file in files)
        {
            // do something
        }
    }
}

【讨论】:

    【解决方案2】:

    检查 SelectedPath 是否有值:

    void refresh() //gets called by button
    {
        if(!String.IsNullOrEmpty(objDialog.SelectedPath))
        {
            listBox1.Items.Clear();
    
            //will cause exception
            var files = System.IO.Directory.GetFiles(objDialog.SelectedPath, "*.*", System.IO.SearchOption.AllDirectories);
    
            foreach (string file in files)
            {
               xxx
            }
            xxx
            xxx
        }
    }
    

    【讨论】:

    • “当点击按钮而不用另一个按钮选择路径时”似乎表明如此
    • 感谢您花时间回答这个简单的问题。你帮了我!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-13
    • 2022-06-16
    • 2011-12-01
    • 2012-05-23
    相关资源
    最近更新 更多