【问题标题】:How to make use of Try and Catch for setting values如何使用 Try 和 Catch 设置值
【发布时间】:2013-05-31 08:17:26
【问题描述】:

如何在Letter 中获取try catch 来调用Program 中的try catch?目前我正在使用 bool 作为验证器,但我希望任何 false bool 都会引发错误,并让 Program 看到这一点。

最好的方法是什么,因为目前Program 无法判断属性是否设置不正确。

Program.cs

        Letter a = new Letter();
        try
        {
            a.StoredChar = '2';
        }
        catch (Exception)
        {
            a.StoredChar = 'a';
        }
        // I want this to print 'a' because the '2' should throw a catch somehow
        // I don't know how to set this up.
        Console.WriteLine(a.StoredChar);

Letter.cs

    class Letter
    {
        char storedChar;

        public char StoredChar
        {
            set { validateInput(value);}
            get { return storedChar;}
        }

        bool validateInput(char x)
        {
            if ( ( (int)x >= 65 && (int)x <= 90 ) || ( (int)x >= 97 && (int)x <= 122 )  )
            {
                storedChar = x;
                return true;
            }
            else
            {
                return false;
            }
        }
    }

【问题讨论】:

  • 这里真正的问题是:'2' 真的是一个意想不到的值,还是你使用异常来驱动你的程序流程?
  • '2' 是一个意外的值,这将由用户输入驱动。

标签: c# validation exception try-catch


【解决方案1】:

只需在 Letter 类中抛出异常。像这样的:

private void validateInput(char x)
{
    if ( ( (int)x >= 65 && (int)x <= 90 ) || ( (int)x >= 97 && (int)x <= 122 )  )
    {
       storedChar = x;
    }
    else
    {
       throw new OutOfRangeException("Incorrect letter!");
    }
}

【讨论】:

  • 这个。就这样做。如果您只是想丢弃价值,请不要费心返回false...
  • 如果我在程序中写catch (Exception e),如何打印“不正确的异常”部分?如果我打印 e 我会得到比字符串更多的额外信息...
  • @Joseph Console.WriteLine(e.Message);
【解决方案2】:

我绝不会使用异常来驱动程序流程。如果允许用户键入可能错误地传递给 Letter 类的值,那么您应该更改您的类以公开 ValidateInput 方法并在尝试更改 StoredChar 之前调用它

char z = '2';
Letter a = new Letter();
if(!a.ValidateInput(z))
{
    MessageBox.Show("Invalid data");
    return;
}
a.StoredChar = z;

【讨论】:

  • 在我的示例中,意外输入将来自用户,这仍然是使用 try..catch 的坏情况吗?
  • 是的,我认为,您迟早需要一个程序来检查用户输入,然后再将它们添加到您的课程中。
  • @Joseph 抛出异常并捕获它会增加不必要的开销。如果您不需要,请不要这样做。只有当应用程序遇到异常时才应该抛出异常。更多信息here
  • @alexw,好点,这是要考虑的另一件事。异常明显减慢了代码的执行速度。
  • 干杯,我没有意识到这是一个很大的减速。
【解决方案3】:

我认为使用try catch 设置值不是一个好主意,但根据您的要求,我认为设置器可以是这样的:

void validateInput(char x)
{
   if (((int)x >= 65 && (int)x <= 90 ) || ((int)x >= 97 && (int)x <= 122))
        {
            storedChar = x;
        }
        else
        {
            throw new SomeException();
        }
}

【讨论】:

  • 不知道为什么我的回答被否决了。但是对于任何认为可以使用 try catch 作为逻辑的人,请参考这篇文章:programmers.stackexchange.com/questions/107723/…
  • SomeException() 是一种方法吗?如果您尝试调用构造函数,那么您应该使用throw new SomeException();
猜你喜欢
  • 1970-01-01
  • 2015-07-07
  • 1970-01-01
  • 2018-11-05
  • 2016-06-15
  • 2018-10-17
  • 1970-01-01
  • 2018-10-10
  • 1970-01-01
相关资源
最近更新 更多