How to: Create an Exception Type That Can be Thrown by Remote Objects

This topic is specific to a legacy technology that is retained for backward compatibility with existing applications and is not recommended for new development. Distributed applications should now be developed using the  Windows Communication Foundation (WCF).

You can create your own exception type that can be thrown by a remote object and caught by a remote caller by deriving from the RemotingException class and implementing the ISerializable interface.

To create an exception type that can be thrown by remote objects and caught by remote callers

  1. Define a class that derives from the RemotingException class.

    public class RemotableType : MarshalByRefObject{
    // ...
    }
    
  2. Place the SerializableAttribute attribute on the class.

    [Serializable]
    public class CustomRemotableException : RemotingException, ISerializable {
        // ...
    }
    
  3. Implement a deserialization constructor that takes a SerializationInfo object and a StreamingContext object as parameters.

    public CustomRemotableException(SerializationInfo info, StreamingContext context) {
          _internalMessage = (string)info.GetValue("_internalMessage", typeof(string));
     }
    

Example

The following code example provides a simple implementation that, if configured, is copied back to the caller when thrown by the remote server object.

[Serializable]
public class CustomRemotableException : RemotingException, ISerializable
{
    private string _internalMessage;

    public CustomRemotableException()
    {
        _internalMessage = String.Empty;
    }

    public CustomRemotableException(string message)
    {
        _internalMessage = message;
    }

    public CustomRemotableException(SerializationInfo info, StreamingContext context)
    {
        _internalMessage = (string)info.GetValue("_internalMessage", typeof(string));
    }

    public override void GetObjectData(SerializationInfo info, StreamingContext context)
    {
         info.AddValue("_internalMessage", _internalMessage);
    }

     // Returns the exception information. 
     public override string Message
     {
         get
         {
             return "This is your custom remotable exception returning: \""
          + _internalMessage
          + "\"";
         }
     }
}

See Also

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2015 Microsoft