10.2. Custom Exceptions

As mentioned earlier, one of the key advantages of exceptions is the ability they give you to track the execution path in the event of a failure. In the previous listings we examined the stack trace and pinpointed what went wrong with the code, but often you need a more descriptive way of logging what went wrong. One quick fix is to print a friendly string to the file, console, or database and later search for that string during troubleshooting. However, searching for a specific string is error-prone because string messages change.

A more elegant way of handling exceptions is to create your own custom exception objects. These objects are like any other C# objects. Listing 10.6 shows a custom exception class.

Listing 10.6. ...

Get .NET for Java Developers: Migrating to C# 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.