Exception Handling Fundamentals in C#.NET

 Exception Handling

Errors in any language are classified into Compile Time Errors, Runtime Errors and Logical Errors.

Compile Time Errors
Compile time errors are the errors that are found during compilation. In general these errors are syntactical errors in the program. It is not possible to execute the program without rectifying the compile time errors. Hence exception handling is not related to compile time errors.

Runtime Errors
Runtime errors are the errors that occur at runtime i.e. while executing the program. These are also called exceptions. When an exception occurs then the program will be terminated abnormally without giving a proper message to the user regarding the exception. Exception handling is used to handle exceptions and give proper message to the user regarding exception and avoid abnormal termination of the program. Exception handling in C# was based on the keywords try , catch, finally and throw.

Try block is used to write the statements that may cause an exception. When an exception was raised in the try block, then control will be taken to catch block where we have to write the exception handling code. Once control reaches the catch block it is not possible to take it back to try. The complete code in the try block will be executed only when there is no exception raised and the code in catch block is executed only when an exception was raised. But you may have the code to be executed both when an exception was raised and no exception was raised. Finally block is used to write this type of code that needs to be executed both when an exception was raised and no exception was raised. Throw is used to raise exceptions manual.

                                    Try
                                    {
                                                                                                                                                                                               
                                    }
Catch
{

}
Finally
{

}
Example : 
The following example accepts two integers and performs division. If the value given for denominator is zero then an exception will be raised and the program handles this exception with exception handling.

namespace ExceptionHandling
{
    class Program
    {
        static void Main(string[] args)
        {
            int A, B, R;
            Console.WriteLine("Enter Two Integers");
            A = int.Parse(Console.ReadLine());
            B = int.Parse(Console.ReadLine());
            try
            {
                R = A / B;
                Console.WriteLine("Ratio Of {0} And {1} Is {2}", A, B, R);
            }
            catch (DivideByZeroException Ex)
            {
                Console.WriteLine("Division With Zero Not Possible");
            }
        }
    }
}

Handling Multiple Exceptions
Within a method there is possibility for more than one exception. In this case no need to write separate try…catch for each exception and related to a single try block you can create any number of catch blocks, one for each type of exception.

Example : 
The following example handles two exceptions dividebyzero exception and overflow exception that will be raised when the value given for variable is out of range for its data type.

namespace ExceptionHandling
{
    class MultipleExceptions
    {
        static void Main()
        {
            int A, B, R;
            Console.WriteLine("Enter Two Integers");
            try
            {
                A = int.Parse(Console.ReadLine());
                B = int.Parse(Console.ReadLine());
                R = A / B;
                Console.WriteLine("Ratio Of {0} And {1} Is {2}", A, B, R);
            }

           catch (DivideByZeroException Ex)
            {
                Console.WriteLine("Division With Zero Not Possible");
            }
            catch (OverflowException Ex)
            {
            Console.WriteLine("Value Must Be Within The Range Of Integer");
            }
            catch (FormatException Ex)
            {
                Console.WriteLine("Value Must Be Numeric");
            }

            Console.Read();
        }
    }
}

Handling Any Type of Exception
A programmer will write the exception handling code for all the exceptions that are up to his expectation. But there is possibility for an exception that was not up to the expectation of the programmer. Hence exception handling will be complete only when there is a catch block that can catch any type of exception. For this you have to create the catch block by specifying the exception type as Exception. Every exception in .net is inherited from Exception class and hence it can catch any type of exception. This type of catch block must be the last catch in a series of catch blocks.

Example : 
The following example handles three exceptions dividebyzeroexception , overflowexception and FormatException and can also handle any other type of exception.

namespace ExceptionHandling
{
    class AnyException
    {
        static void Main()
        {
            int A, B, R;
            Console.WriteLine("Enter Two Integers");
            try
            {
                A = int.Parse(Console.ReadLine());
                B = int.Parse(Console.ReadLine());
                R = A / B;
                Console.WriteLine("Ratio Of {0} And {1} Is {2}", A, B, R);
            }
            catch (DivideByZeroException Ex)
            {
                Console.WriteLine("Division With Zero Not Possible");
            }
            catch (OverflowException Ex)
            {
            Console.WriteLine("Value Must Be Within The Range Of Integer");
            }
            catch (Exception Ex)
            {
                Console.WriteLine(Ex.Message);
            }
            Console.Read();
        }
    }
}

User Defined Exceptions
There may be a situation where system will not raise an exception for your requirement and you want to raise the exception manual. In this case you have to create a class for your exception and it must be inherited from Exception class. To raise the exception, use throw keyword.

Example : 
The following example creates a user defined exception that will be raised when user enters a negative value for either A or B.

namespace ExceptionHandling
{
    class MyException : Exception
    {
        public string MyMessage;
        public MyException(string Mes)
        {
            MyMessage = Mes;
        }
    }
    class UserExceptions
    {
        static void Main()
        {
            int A, B, R;
            Console.WriteLine("Enter Two Integers");
            try
            {
                A = int.Parse(Console.ReadLine());
                if(A<0)
                    throw new MyException("-ve Values Are Not Allowed");
                B = int.Parse(Console.ReadLine());
                if(B<0)
                    throw new MyException("-ve Values Are Not Allowed");
                R = A / B;
                Console.WriteLine("Ratio Of {0} And {1} Is {2}", A, B, R);
            }
            catch (DivideByZeroException Ex)
            {
                Console.WriteLine("Division With Zero Not Possible");
            }
            catch (OverflowException Ex)
            {
            Console.WriteLine("Value Must Be Within The Range Of Integer");
            }
            catch(MyException Ex)
            {
                Console.WriteLine(Ex.MyMessage);
            }
            catch (Exception Ex)
            {
                Console.WriteLine(Ex.Message);
            }           
            Console.Read();
        }
    }
}

Logical Errors
Logical error is an error that will not be found during compilation or at runtime and will cause the program output to be wron. To find and rectify the logical errors tracing and debugging is used. Executing the program step by step and finding logical errors is called as tracing and debugging. To execute the program step by step shortcut is F11.


Thanks for visiting this blog. How is the content?. Your comment is great gift to my work. Cheers.

No comments:

Post a Comment