- C# 7 and .NET Core Cookbook
- Dirk Strauss
- 139字
- 2021-07-03 00:11:57
How to do it...
- 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");
}
- 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);
}
- Running your console application will then return the exception message as the output.

推薦閱讀
- Getting Started with React
- Java程序設(shè)計與計算思維
- Java Web應(yīng)用開發(fā)技術(shù)與案例教程(第2版)
- 精通Python設(shè)計模式(第2版)
- RISC-V體系結(jié)構(gòu)編程與實踐(第2版)
- Android開發(fā)案例教程與項目實戰(zhàn)(在線實驗+在線自測)
- 持續(xù)集成與持續(xù)交付實戰(zhàn):用Jenkins、Travis CI和CircleCI構(gòu)建和發(fā)布大規(guī)模高質(zhì)量軟件
- Java并發(fā)編程之美
- 現(xiàn)代C:概念剖析和編程實踐
- 監(jiān)控的藝術(shù):云原生時代的監(jiān)控框架
- Python編程快速上手2
- MySQL數(shù)據(jù)庫應(yīng)用實戰(zhàn)教程(慕課版)
- Cinder:Begin Creative Coding
- Apache Kafka 1.0 Cookbook
- Learning Zimbra Server Essentials