Monday, 29 October 2012

Create and Handle Custom Exception Class in your application in .Net with C# Examples and VB.Net Examples

 Click Here to Download ImplementCustomException.zip
You can also called that create user defined exception class in asp.net.
There is a situations where you need to create and handle a custom exception for handling runtime’s exception for application-specific exceptions.
In this example we provide both C#.Net Example and VB.Net Example.

Let's look how this mechanism works.
For that we need to create a serializable class that extends the System.Exception class, and ass some constructors and properties to manipulate the data members.
You can throw custom exception class object exception in Try block and it will handle in catch block. Mark your custom exception class as sealed if you do not wish other exception classes to extend it. You need to Implement three public constructors with specific signature and they call base class constructor.

You also need to make custom exception class serializable so that the runtime can marshal instances of your exception. If your exception class declares custom data members, so you must override the ISerializable. GetObjectData method of the Exception class as well as implement a deserialization constructor with appropriate signature. If your exception class is sealed then mark the deserialization constructor as private, otherwise, mark it as protected. The GetObjectData method and deserialization constructor must call the equivalent base class method to allow the base class to serialize and deserialize its data correctly.

Here is example for this.

In this example we take one custom "CustomException" class and raise errors from try block and handle this error in Catch block. You can also make your own data members and constructors in "CustomException" class.


C# Examples :
using System.Runtime.Serialization;

public sealed class CustomException : Exception
{
    
    // Custom data members for CustomException.
    private string stringInfo;
    private bool booleanInfo;
    // Three standard constructors and simply call the base class.

    public CustomException() : base() { }
    public CustomException(string strMessage) : base(strMessage) { }
    public CustomException(string strMessage, Exception inner): base(strMessage, inner) { }

    
    private CustomException(SerializationInfo info,StreamingContext context): base(info, context)
    {
        // Deserialize each custom data member.
        stringInfo = info.GetString("StringInfo");
        booleanInfo = info.GetBoolean("BooleanInfo");
    }

    // Additional constructors to allow code to set the custom data members.
    public CustomException(string message, string stringInfo,bool booleanInfo): this(message)
    {
        this.stringInfo = stringInfo;
        this.booleanInfo = booleanInfo;
    }

    public CustomException(string message, Exception inner,string stringInfo, bool booleanInfo): this(message, inner)
    {
        this.stringInfo = stringInfo;
        this.booleanInfo = booleanInfo;
    }

    // Read-only properties that provide access to the custom data members.
    public string StringInfo
    {
        get { return stringInfo; }
    }
    public bool BooleanInfo
    {
        get { return booleanInfo; }
    }
    
    public override void GetObjectData(SerializationInfo info,StreamingContext context)
    {
        // Serialize the custom data members.
        info.AddValue("StringInfo", stringInfo);
        info.AddValue("BooleanInfo", booleanInfo);
        // Call the base class to serialize its members.
        base.GetObjectData(info, context);
    }
    
    public override string Message
    {
        get
        {
            string message = base.Message;
            if (stringInfo != null)
            {
                message += "<br/> String Info : " +stringInfo + "<br/> Boolean Info : " + booleanInfo;
            }
            return message;
        }
    }
}

    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            // Create and throw a CustomException object.
            throw new CustomException("Some Custom Exception Message", "Some String Info", true);

        }
        catch (CustomException ex)
        {
            Response.Write(ex.Message);
        }
        
    }

VB.Net Examples :

Imports System.Runtime.Serialization
    Public NotInheritable Class CustomException
        Inherits Exception

        ' Custom data members for CustomException.
        Private m_stringInfo As String
        Private m_booleanInfo As Boolean
        ' Three standard constructors and simply call the base class.

        Public Sub New()
            MyBase.New()
        End Sub
        Public Sub New(ByVal strMessage As String)
            MyBase.New(strMessage)
        End Sub
        Public Sub New(ByVal strMessage As String, ByVal inner As Exception)
            MyBase.New(strMessage, inner)
        End Sub


        Private Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext)
            MyBase.New(info, context)
            ' Deserialize each custom data member.
            m_stringInfo = info.GetString("StringInfo")
            m_booleanInfo = info.GetBoolean("BooleanInfo")
        End Sub

        ' Additional constructors to allow code to set the custom data members.
        Public Sub New(ByVal message As String, ByVal stringInfo As String, ByVal booleanInfo As Boolean)
            Me.New(message)
            Me.m_stringInfo = stringInfo
            Me.m_booleanInfo = booleanInfo
        End Sub

        Public Sub New(ByVal message As String, ByVal inner As Exception, ByVal stringInfo As String, ByVal booleanInfo As Boolean)
            Me.New(message, inner)
            Me.m_stringInfo = stringInfo
            Me.m_booleanInfo = booleanInfo
        End Sub

        ' Read-only properties that provide access to the custom data members.
        Public ReadOnly Property StringInfo() As String
            Get
                Return m_stringInfo
            End Get
        End Property
        Public ReadOnly Property BooleanInfo() As Boolean
            Get
                Return m_booleanInfo
            End Get
        End Property

        Public Overrides Sub GetObjectData(ByVal info As SerializationInfo, ByVal context As StreamingContext)
            ' Serialize the custom data members.
            info.AddValue("StringInfo", m_stringInfo)
            info.AddValue("BooleanInfo", m_booleanInfo)
            ' Call the base class to serialize its members.
            MyBase.GetObjectData(info, context)
        End Sub

        Public Overrides ReadOnly Property Message() As String
            Get
                Dim message__1 As String = MyBase.Message
                If m_stringInfo IsNot Nothing Then
                    message__1 += "<br/>String Info : " & m_stringInfo & " <br/> Boolean Info : " & m_booleanInfo
                End If
                Return message__1
            End Get
        End Property
    End Class

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Try
            ' Create and throw a CustomException object.

            Throw New CustomException("Some Custom Exception Message", "Some String Info", True)
        Catch ex As CustomException
            Response.Write(ex.Message)
        End Try
    End Sub

Output :


This article is very useful for Beginning .Net.

Note : Give Us your valuable feedback in comments. Give your suggestions in this article so we can update our articles accordingly that.




No comments:

Post a Comment