Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

Part 42 - C# Tutorial - Custom Exceptions

In this part we will learn 
1. When to create custom exceptions
2. Creating a custom exception from the scratch
3. Throwing and catching the custom exception


To understand custom exceptions, you should have good understanding of
Part 21 - Inheritance
Part 40 - Exception Handling Basics
Part 41 - Inner Exceptions
Part 42 - C# Tutorial - Custom Exceptions



When do you usually go for creating your own custom exceptions?
If none of the already existing dotnet exceptions adequately describes the problem. 


Consider that
1. I have an asp.net web application.
2. The application should allow the user to have only one logged in session.
3. If the user is already logged in, and if he opens another browser window and tries to login again, the application should throw an error stating he is already logged in another browser window.


With in the .NET framework we donot have any exception, that adequately describes this problem. So this scenario is one of the examples where you want to create a custom exception.


We know that an exception is a class. So to create a Custom exception, 
1. Create a class that derives from System.Exception class. As a convention, end the class name with Exception suffix. All .NET exceptions end with,  exception suffix. If you don't do so, you won't get a compiler error, but you will be deviating from the guidelines for creating custom exceptions.
public class UserAlreadyLoggedInException : Exception
{
}


2. Provide a public constructor, that takes in a string parameter. This constructor simply passes the string parameter, to the base exception class constructor.
public UserAlreadyLoggedInException(string message)
        : base(message)
{
}


3. Using InnerExceptions, you can also track back the original exception. If you want to provide this capability for your custom exception class, then overload the constructor as shown below. If you are new to Constructor Overloading, please watch this video.
public UserAlreadyLoggedInException(string message, Exception innerException)
    : base(message, innerException)
{
}


4. If you want your Exception class object to work across application domains, then the object must be serializable. To make your exception class serializable mark it with Serializable attribute and provide a constructor that invokes the base Exception class constructor that takes in SerializationInfo and StreamingContext objects as parameters.
[Serializable]
public class UserAlreadyLoggedInException : Exception
{
    public UserAlreadyLoggedInException(SerializationInfo info, StreamingContext context)
        : base(info, context)
    {
    }
}


Note: It is also possible to provide your own custom serialization, which will discuss in a later session.


Complete Example of creating a custom exception:
using System;
using System.Runtime.Serialization;


public class CustomExceptions
{
    public static void Main()
    {
        try
        {
            throw new UserAlreadyLoggedInException("User Already logged in");
        }
        catch (UserAlreadyLoggedInException ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}


[Serializable]
public class UserAlreadyLoggedInException : Exception
{
    public UserAlreadyLoggedInException(string message)
        : base(message)
    {
    }


    public UserAlreadyLoggedInException(string message, Exception innerException)
        : base(message, innerException)
    {
    }
    
    public UserAlreadyLoggedInException(SerializationInfo info, StreamingContext context)
        : base(info, context)
    {
    }
}

5 comments:

  1. In which you will discuss Application Domain.

    ReplyDelete
  2. hi sir ,small doubts

    public UserAlreadyLoggedInException(string message)
    : base(message)
    {
    }


    public UserAlreadyLoggedInException(string message, Exception innerException)
    : base(message, innerException)
    {
    }

    public UserAlreadyLoggedInException(SerializationInfo info, StreamingContext context)
    : base(info, context)
    {
    }
    }all constructor is inherit with this :base(info,context or anything) why this line adding pls say sir,iam already seen inheritance videos...

    sorry for my bad english...

    ReplyDelete
    Replies
    1. is to ensure to call base class constructor so that message, innerExceptions etc initialized properly in base class default behavior. plz let me know if you need further clarification.

      Delete
    2. it is syntax to call base class constructor, here it will call Exception class constructor before your custom Exception class constructor to ensure proper values initialization.

      Delete
  3. Hello Sir,
    I got to know that if we use use only try { } catch { } ,ie. catch without () paranthisis then all the exceptions that occurs in try block(System + Custom ) can be catched in catch block.
    My question is,
    1) Is it True..?
    2) If yes, then how to use it..??

    Thank You ...

    ReplyDelete

It would be great if you can help share these free resources