How to Handle a Custom Exception in C#

Introduction
The exceptions are anomalies that occur during the execution of a program.Exception handling is a mechanism in .NET framework to detect and handle run time errors. They can be because of user, logic or system errors. If a user (programmer) does not provide a mechanism to handle these anomalies, the .NET runtime environment provides a default mechanism, which terminates the program execution.

In C# there are three keywords Try, Catch and Finally for handling exceptions.



Exception Class

Following are some common exception classes.
  1. SystemException- This exception means a failed run-time check used as a base class for other. 
  2. AccessException- This exception means failure to access a type member, such as a method or field. 
  3. ArithmeticException- This exception means arithmetic over or underflow has occurred.
  4. DivideByZeroException- This exception means an attempt was made to divide by zero. 
  5. FormatException- This exception means the format of an argument is wrong. 
  6. IndexOutOfRangeException- This exception means an array index is out of bounds. 
  7. NotSupportedException- This exception indicates that a method is not implemented by a class. 
  8. NullReferenceException- This exception means attempt to use an unassigned reference. 
  9. OutOfMemoryException- This exception means not enough memory to continue execution.
  10. StackOverflowException- This exception means a stack has overflow.


Custom Exception

  • Although the .NET framework contains all kinds of exception types which are sufficient in most cases, it can make sense to define custom exceptions in your own applications. They can greatly simplify and improve the error handling and thus increase the overall code quality. Generally, for large scale projects (i.e. having multiple modules talks to each other), one should define custom exceptions. 
  • For Implementing Custom Exception Handling, we need to derive the class CustomException from the system Base Class ApplicationException. 
  • Any Custom Exception you create needs to derive from the System.Exception class. You can either derive directly from it or use an intermediate exception like SystemException or ApplicationException as base class.


Steps to Create Custom Exception
  1. Implement error handling in the user interface. 
  2. Create and implement custom error messages. 
  3. Create and implement custom error handlers. 
  4. Raise and handle errors.

Example:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CustomExceptionDemo
{
    sealed class MyException : Exception
    {
        private string myMessage= string.Empty;
        public string MyMessage
        {
         get{
             return myMessage;
         }
            set{
            myMessage=value;
            }
       }
    }
    class abc
    {
        public void checkSalary(int sal)
        {
            if (sal > 15000)
            {
                MyException myexobj = new MyException()
                {
                    MyMessage = "salary out of bound"
                };
                throw myexobj;
            }
            else
            {
                Console.WriteLine("salary =" + sal);
            }
        }
    }



    class Program
    {
        static void Main()
        {
            int sal;
            Console.WriteLine("Entry the salary");
            sal= Convert.ToInt32(Console.ReadLine());
            abc obj = new abc();
            try
            {
                obj.checkSalary(sal);
            }
            catch(MyException exc)
            {
                Console.WriteLine(exc.MyMessage);
            }
            Console.ReadKey();
        }
    }
}




Output:-

No comments:

Post a Comment

Xamarin Android Project App

Xamarin Android Project App 1. Xamarin -- Make a CALCULATOR Android App   https://drive.google.com/open?id=0B8OPCXLrtKPmWC1FWWtFM2lraVk...