我如何能够在Letter中尝试捕获一个程序中的try catch?目前我使用bool作为验证器,但我想要任何假bool抛出错误,并且程序看到这个.
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; } } }
解决方法
只需在Letter类中抛出异常.像这样的Smth:
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!"); } }