我是编程新手,正在尝试找出如何捕获错误“FileNotFoundException”。我的代码是搜索现有的文本文档(从文本框中键入的内容)并将其加载到我的listbox1中。我把这个问题解决了。然而,一个新的问题出现了!如果用户输入了错误的名称/数字,应用程序就会崩溃,并显示找不到该文件的错误。有没有办法让程序显示错误消息“找不到文件”。或者干脆不让整个程序崩溃?提前感谢!
private void btnEnter_Click(object sender, EventArgs e)
{
FileInfo file = new FileInfo(txtExisting.Text + ".txt");
StreamReader stRead = file.OpenText();
while (!stRead.EndOfStream)
{
listBox1.Items.Add(stRead.ReadLine());
}
}发布于 2016-05-07 09:31:55
您应该使用try-catch语句来处理异常。
private void btnEnter_Click(object sender, EventArgs args)
{
try
{
FileInfo file = new FileInfo(txtExisting.Text + ".txt");
StreamReader stRead = file.OpenText();
while (!stRead.EndOfStream)
{
listBox1.Items.Add(stRead.ReadLine());
}
}
catch (FileNotFoundException e)
{
// FileNotFoundExceptions are handled here.
}
}基本上,try块中的代码将按正常方式执行,但如果出现错误,将执行catch块,特别是:
当引发异常时,公共语言运行库查找处理此异常的catch语句。
这意味着,如果您希望遇到不同类型的异常,则try-catch语句可以有多个catch块,以便可以相应地处理它们。
更多信息可以在here上找到。
至于UX,如果能通过显示一条消息来告知用户出了什么问题,那就太好了。
发布于 2016-05-07 09:58:31
只需在btnEnter_Click函数中使用您的代码添加一个try/catch块,如下所示:
try
{
//your code here
}
catch (FileNotFoundException ex)
{
MessageBox.Show(ex.Message);//if you want to show the exception message
}
catch (Exception ex1)
{
/* Exceptions other than the above will be handled in this section,
this should be used when you are not aware the type of exception
can occur in your code for a safe side*/
}发布于 2016-05-07 09:31:24
使用try/catch语句:
private void btnEnter_Click(object sender, EventArgs e)
{
try
{
FileInfo file = new FileInfo(txtExisting.Text + ".txt");
StreamReader stRead = file.OpenText();
while (!stRead.EndOfStream)
{
listBox1.Items.Add(stRead.ReadLine());
}
}
catch (FileNotFoundException ex)
{
// Handle exception
}
}https://stackoverflow.com/questions/37083545
复制相似问题