c# - 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)
进一步的代码中找不到。
我究竟做错了什么?
解决方案
你不应该吞下异常。它们通常包含有关究竟出了什么问题的信息。不要以非常奇怪的方式处理异常,您应该首先通过检查目录是否存在来避免它:
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
}
}
}
推荐阅读
- python - 如何在处理列表时使用 .pop 和 .append 进行 FIFO(而不是 LIFO)?
- sql-server - 没有公共字段的连接表
- java - 在 android studio 上的 SQLITE 中使用 Like 语句
- javascript - 使用cheerio访问特定的div
- r - R 在使用 cv.tree() 时遇到致命错误
- mysql - 无法插入 MySQL
- sql - 有没有办法将两个条件与 SSRS 颜色表达式结合起来?
- sql - SUMIF、分组依据、聚合依据
- php - 提交日期输入自动 1969 年 12 月 31 日,留空
- css - 有没有办法在构建 Visual Studio 项目时自动删除未使用的 CSS 规则?