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

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.
主站蜘蛛池模板: 思南县| 运城市| 德阳市| 东兴市| 浦城县| 南漳县| 开阳县| 常山县| 夹江县| 永修县| 西乌| 远安县| 扶绥县| 霞浦县| 禹州市| 霍城县| 磐石市| 香河县| 安乡县| 夹江县| 安庆市| 沙雅县| 长沙市| 常熟市| 城步| 定远县| 南阳市| 渭南市| 秦安县| 湘乡市| 凌云县| 承德县| 新巴尔虎左旗| 禹州市| 麻江县| 绥棱县| 瑞安市| 于都县| 调兵山市| 炎陵县| 林西县|