C#忽略异常

时间:2018-08-07 08:13:54

标签: c# exception try-catch

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

 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)中的

我在做什么错了?

2 个答案:

答案 0 :(得分: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
        }
    }

答案 1 :(得分:0)

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