How to Create Custom Exception in C# .net program? Use of it?

Implementation of user defined or custom exception in C# .net programming is simple and is implemented by extending system Exception class. We’ll answer concept of run time custom exception with a program example in C#.

Custom Exception Class

Custom Exception class is nothing but a user defined class which is derived from System Exception class. Here are steps

  • Derive a Custom class from System Exception class.
  • Create a constructor of custom class with error message parameter and pass it to the base class (System Exception class).
  • Throw and catch custom exception message in try catch block in C# wherever is required.
//custom exception class or user defined Exception class.
    class UnwantedCharException : Exception
    {
        //create custruction and pass a error message to 
        //base class i.e.System exception class
        public UnwantedCharException(String msg) : base(msg) { }
    }

Complete C# Program for Custom Exception

Let’s understand the concept with simple example. Below program will accept a string from user and if the string is alphanumeric, program will be processed or else it will throw a custom exception that “Only Alphanumeric string is allowed”

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace CustomException
{
    //custom exception class or user defined Exception class.
    class UnwantedCharException : Exception
    {
        //create custruction and pass a error message to 
        //base class i.e.System exception class
        public UnwantedCharException(String msg) : base(msg) { }
    }

    //Test Program
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                string s = GetInputString();

                //process further if no exception.
                Console.WriteLine(s);

            }
            catch (UnwantedCharException ex)
            {
                //Get custom exception
                Console.WriteLine(ex.Message);

            }

        }

        static string GetInputString()
        {
            string s = Console.ReadLine();
            //User String is not alphnumeric, throw Exception.
            if (!IsAlphaNumeric(s))
            {
                throw new UnwantedCharException("Only Alphanumeric string is allowed");
            }

            return s;
        }
        public static bool IsAlphaNumeric(String strToCheck)
        {
            Regex objAlphaNumericPattern = new Regex("[^a-zA-Z0-9]");
            return !objAlphaNumericPattern.IsMatch(strToCheck);
        }
    }


}

NOTE:

This custom exception handling in C# interview question can also be asked as how to create user defined exception in C# or why we use custom exception or why do we need it in C# project or how to throw or handle custom run time exception message etc.

Why do we need Custom Exception in C# applications?

There are tons of exceptions available in C# .net framework e.g. FileFormatException, FileNotFoundException and DriveNotFoundException etc. However, sometime we need to write our own custom exception class in an application. For example, let’s say during database processing, error code is thrown for resource is busy or table is full etc.  and since, error code may not be understandable to customer, so we may want to throw meaning full run time exception, so, customer or end user can understand it.

Related Posts