- 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.

推薦閱讀
- Flutter開發實戰詳解
- Web開發的貴族:ASP.NET 3.5+SQL Server 2008
- Instant Typeahead.js
- PHP 編程從入門到實踐
- Spring Cloud、Nginx高并發核心編程
- 人臉識別原理及算法:動態人臉識別系統研究
- Learning Apache Kafka(Second Edition)
- QGIS:Becoming a GIS Power User
- Mastering Akka
- Microsoft 365 Certified Fundamentals MS-900 Exam Guide
- Mastering Docker
- Instant GLEW
- Hands-On Dependency Injection in Go
- Unity虛擬現實開發圣典
- Python High Performance(Second Edition)