首页 > 解决方案 > C# 忽略异常

问题描述

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

 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)进一步的代码中找不到。

我究竟做错了什么?

标签: c#exceptiontry-catch

解决方案


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

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

推荐阅读