如何输入和异常

本文关键字:异常 输入 何输入 | 更新日期: 2023-09-27 18:32:23

好的,这是我正在处理的代码。我正在尝试获得一个例外,这样如果他们在盒子里没有东西可以保存它,它会弹出并且不让他们继续前进,直到把东西放在那里。现在我知道当我运行我的程序并单击保存按钮时,它会告诉我这一点

参数异常未处理

那是什么意思。我知道它说空路径名是不合法的。但路径是用户想要的。我一直在搞砸这个,我试图弄清楚该怎么做,但仍然有点困惑。那么尝试去做的最好方法是什么。我是否必须创建一个类才能使其工作,或者我可以添加到我的代码中。我通过尝试和捕获修复了另一部分,但我无法让它在这个部分上工作,或者我可能把它放在了错误的位置。

private void Save_Click(object sender, EventArgs e)
{
    string path = txtFilePath.Text;    
    if (!File.Exists(path))
    {
        using (StreamWriter sw = File.CreateText(path))          
        {
            foreach (string lines in employeeList.Items)
                sw.WriteLine(lines);
        }
        else
        {
            using (StreamWriter sw = File.AppendText(path))<--This is 
where is says Arugment exception was unhandled.              
            {    
                foreach (var item in employeeList.Items)
                    sw.WriteLine(item.ToString());
            }
        }
    }
}

如何输入和异常

代码包装在 try catch 语句中,在 catch 中,您可以生成一条消息给用户(可能是 javascript 警报框)

伪代码...

try
{
    current code
}
catch (exception e)
{
    error message to user
}
这意味着

path 是长度为零的字符串,仅包含空格或包含 由无效路径字符定义的一个或多个无效字符。

if(path == "")
{
    // Alert user or throw Exception
}

你的"路径"不严重。

ArgumentException   
path is a zero-length string, contains only white space, or contains one or more invalid characters as defined by InvalidPathChars.

http://msdn.microsoft.com/ru-ru/library/system.io.path.invalidpathchars.aspx

使用

private void Save_Click(object sender, EventArgs e)
{
  if (!string.IsNullorEmpty(txtFilePath.Text))
  {
    MessageBox.Show("Please enter new path");
    txtFilePath.Focus();
    return;
  }
  else
  {
    string path = txtFilePath.Text;
      if (!File.Exists(path))
        {
           ..... Your rest code

我知道这是一个旧帖子,但我想无论如何我都会回答。

上面的代码的所有问题都是在错误的地方有一个 }。

If (not file exists)
{
   else 
   {
   }
}

其他应该再下降一点。

if(not file exists)
{
}
else
{
}