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

推薦閱讀
- Java 9 Concurrency Cookbook(Second Edition)
- Python數(shù)據(jù)分析入門與實戰(zhàn)
- ASP.NET MVC4框架揭秘
- Microsoft Application Virtualization Cookbook
- Windows Server 2012 Unified Remote Access Planning and Deployment
- C++程序設(shè)計基礎(chǔ)教程
- Ext JS 4 Web Application Development Cookbook
- Learning Apache Mahout Classification
- Android系統(tǒng)級深入開發(fā)
- C#程序設(shè)計教程(第3版)
- 區(qū)塊鏈國產(chǎn)化實踐指南:基于Fabric 2.0
- Learning VMware vSphere
- Java Web開發(fā)實例大全(基礎(chǔ)卷) (軟件工程師開發(fā)大系)
- Android Game Programming by Example
- 進入IT企業(yè)必讀的324個Java面試題