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

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.
主站蜘蛛池模板: 安化县| 汉川市| 五莲县| 榆社县| 宜州市| 阿勒泰市| 上蔡县| 南江县| 临漳县| 绥芬河市| 平舆县| 新安县| 仁寿县| 阿瓦提县| 高雄市| SHOW| 海淀区| 齐河县| 长沙市| 义马市| 闵行区| 乐东| 长治市| 甘孜| 波密县| 城口县| 临清市| 抚宁县| 吴堡县| 西乌珠穆沁旗| 阳信县| 汉中市| 乌鲁木齐县| 德格县| 乌鲁木齐县| 奎屯市| 封开县| 定南县| 博湖县| 微山县| 晋宁县|