Home > DeveloperSection > Blogs > Exceptional Handling in c#

Exceptional Handling in c#


C# C# 
Ratings:
2 Comment(s)
 152  View(s)
Rate this:

Exceptional Handling in c#


Exceptional handling in c# is used when there is any chance of dynamic error occurs while executing the program.

There are three block provided by the C# to handle exception.


Try

Catch

Finally

 

Try: In this block particular exception is activated. This block is used to raise the exception. If such exception does not exist, then an error will accrue. Most of the coding part is done in this block. When an exception is raised by the try block, then CLR looks for the catch statement that handles the exception. If no such error found by then CLR displays an unhandled exception message and stop execution of the  program.

 

Catch: If CLR found the exceptions then catch block activated for those we are getting exceptions that you know how to recover from. hence, one should always specify an object argument.

 

Finally: This block is also a very important block because all the instances or objects get disposed in this block. It doesn't matter exception is found or not this block will definitely execute.

 

There are many predefined exceptions in C#, which we can use in our programming. I have created the program related to each of them. They are as follows:

 

IndexOutOfRangeException

 
namespace ErrorHandlingProgram
{
    class HandleError
    {
        static void Main(string[] args)
        {
            int[] num1 = new int[2];
           
            try
            {
                num1[0] = 23;
                num1[1] = 0;
                num1[2] = 45;
            }
            catch (IndexOutOfRangeException ex)
            {
                Console.WriteLine("An index was out of range!  "+ex);
            }
           
            finally
            {
                Console.WriteLine("Clean Up is completed");
            }
            Console.ReadLine();
        }
    }
}

 

 OutOfMemoryException

namespace ErrorHandlingProgram
{
    class HandleError
    {
        static void Main(string[] args)
        {
            int[] num1 = new int[2];
           
            try
            {
                string a = new string('b', int.MaxValue); //I require 4.2 billion bytes (4 gigabytes).
            }
           
            catch (OutOfMemoryException ex)
            {
                Console.WriteLine("OutOfMemoryException error occured: "+ ex.Message);
            }
           
            finally
            {
                Console.WriteLine("Clean Up is completed");
            }
            Console.ReadLine();
        }
    }
}

NullReferenceException

namespace ErrorHandlingProgram
{
    class HandleError
    {
        static void Main(string[] args)
        {
            try
            {
 
                string a = null;
                if (a.Length == 0)
                {
                    Console.WriteLine("Success");
                }
            }
            catch (NullReferenceException ex)
            {
                Console.WriteLine("NullReferenceException error occured: " + ex.Message);
            }
            finally
            {
                Console.WriteLine("Clean Up is completed");
            }
            Console.ReadLine();
        }
    }
}

ArithmeticException

namespace ErrorHandlingProgram
{
    class HandleError
    {
        static void Main(string[] args)
        {
            int a = 1, b = 0;
 
            try
            {
                int c = a / b;
            }
            catch (ArithmeticException ex)
            {
                Console.WriteLine("ArithmeticException error occured: " + ex.Message);
            }
            finally
            {
                Console.WriteLine("Clean Up is completed");
            }
            Console.ReadLine();
        }
    }
}

DivideByZeroException

namespace ErrorHandlingProgram
{
    class HandleError
    {
        static void Main(string[] args)
        {
            int a = 1, b = 0;
 
            try
            {
                int c = a / b;
            }
            catch (DivideByZeroException ex)
            {
                Console.WriteLine("DivideByZeroException error occured: " + ex.Message);
            }
            finally
            {
                Console.WriteLine("Clean Up is completed");
            }
            Console.ReadLine();
        }
    }
}

How to create user defined Exception :

using System; 
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace ErrorHandlingProgram
{
 
    class universalerror1 : Exception
    {
        public universalerror1(String message) : base(message)
        {
        }
    }
    class testexp
    {
        public int a;
 
        public void strgerr()
        {
            if (a == 0)
            {
                throw (new universalerror1("please check"));
            }
            else
            {
                Console.WriteLine(" error is not there");
            }
        }
    }
 
    class Program
    {
 
        static void Main(string[] args)
        {
 
            testexp exp1 = new testexp();
            try
            {
                exp1.a = 0;
                exp1.strgerr();
 
            }
            catch (universalerror1 e)
            {
                Console.WriteLine("Error {0}", e.Message);
            }
            finally
            {
                Console.WriteLine("Clean Up is completed");
            }
            Console.ReadLine();
        }
    }
}




Exceptional Handling using try catch

By aditya kumar Patel on   2 months ago
it is use full.

Exceptional Handling using try catch

By Abhishek Srivasatava on   2 months ago
Nice explanation. very helpful.

Don't want to miss updates? Please click the below button!

Follow MindStick