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; ...
Get C# Cookbook 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.