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

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.
主站蜘蛛池模板: 年辖:市辖区| 芜湖市| 襄垣县| 双桥区| 桃园县| 漳浦县| 五华县| 合阳县| 探索| 云霄县| 安义县| 定结县| 宜丰县| 定安县| 湖北省| 和平县| 确山县| 内乡县| 万载县| 嵊泗县| 九台市| 华安县| 行唐县| 都昌县| 隆化县| 盐边县| 珲春市| 德令哈市| 上杭县| 北川| 玉环县| 辰溪县| 绥芬河市| 瑞丽市| 宁安市| 工布江达县| 上思县| 察哈| 新民市| 潢川县| 水城县|