官术网_书友最值得收藏!

How to do it...

  1. To illustrate the use of a throw expression, create a method called GetNameLength() in the Chapter1 class. All it does is check to see if the length of a name is not zero. If it is, then the method will throw an exception right there in the expression.
        public int GetNameLength(string firstName, string lastName)
{
return (firstName.Length + lastName.Length) > 0 ?
firstName.Length + lastName.Length : throw new
Exception("First name and last name is empty");
}
  1. To see the throw expression in action, create an instance of the Chapter1 class and call the GetNameLength() method. Pass it two blank strings as parameters.
        try
{
Chapter1 ch1 = new Chapter1();
int nameLength = ch1.GetNameLength("", "");
}
catch (Exception ex)
{
WriteLine(ex.Message);
}
  1. Running your console application will then return the exception message as the output.
主站蜘蛛池模板: 武山县| 石门县| 阳高县| 大英县| 临高县| 横峰县| 当涂县| 诏安县| 宁武县| 泾源县| 拉萨市| 莱芜市| 安康市| 曲沃县| 南溪县| 湖州市| 南溪县| 吉林市| 平原县| 丘北县| 沧州市| 中山市| 南投市| 成武县| 从江县| 东乌| 长春市| 邓州市| 新干县| 康定县| 石柱| 兴山县| 新泰市| 台山市| 乌什县| 航空| 西藏| 罗平县| 台东县| 绥德县| 新丰县|