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

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
       Inherits MarshalByRefObject
    
      Implements ISerializable
' ...
End Class 'RemotableType
    Public Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext)
        _internalMessage = info.GetValue("_internalMessage", GetType(String))
    End Sub
   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

Community Additions

ADD
Show:
© 2016 Microsoft