Designing Your Own Exceptions

A program is not limited to the predefined C# exceptions. It's possible to create unique exceptions, tailored to a specific application. This section shows how to design your own exception. Listing 10.6 shows how to create a new exception and how to use it.

Listing 10.6. Designing an Exception: NewException.cs
 using System; using System.IO; public class TooManyItemsException : Exception { public TooManyItemsException() : base(@" **TooManyItemsException** You added too many items to this container. Try specifying a smaller number or increasing the container size. ") { } } public class ExceptionTester { public static int Main(string[] args) { ExceptionTester myExceptionMaker = new ExceptionTester(); try { myExceptionMaker.GenerateException(5); ...

Get C# Unleashed now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.