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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.