O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

5.13. Creating a New Exception Type

Problem

None of the built-in exceptions in the .NET Framework provide the implementation details that you require for an exception that you need to throw. You need to create your own exception class that operates seamlessly with your application, as well as other applications. Whenever an application receives this new exception, it can inform the user that a specific error occurred in a specific component. This report will greatly reduce the time required to debug the problem.

Solution

Create your own exception class. To illustrate, we’ll create a custom exception class, RemoteComponentException, that will inform a client application that an error has occurred in a remote server assembly. The complete source code for the RemoteComponentException class is:

using System; using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; [SerializableAttribute] public class RemoteComponentException : ApplicationException, ISerializable { // New exception field private string serverName = ""; // Normal exception ctor's public RemoteComponentException( ) : base( ) { } public RemoteComponentException(string message) : base(message) { } public RemoteComponentException(string message, Exception innerException) : base(message, innerException) { } // Exception ctor's that accept the new ServerName parameter public RemoteComponentException(string message, string serverName) : base(message) { this.serverName = serverName; ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required