Topic : Exception handling in C#: Try | Catch | Finally | Throw

Exception handling:

Sometimes, Methods or Code not working properly even mine. Most beginning Programmers assume that their programs will work as Expected. On the other side, Experienced programmers know that sometimes things go unexpectedly. if we issue a command to read a file from a disk, the file might not exist. or if we want to write to a disk, the disk might be full or unformatted. if the programs ask for user input, users might enter invalid data.

Such errors that occur during the Execution of Object-Oriented Programming are called Exceptions. and the techniques to manage such errors comprise the group of method known as Exception Handling.


Image: Exception Handling:

C# Exception handling is built upon four keywords, try , catch , throw and finally. The General idea is that, code which has the Potential to go wrong in some way is wrapped in a try block, using the throw keyword when it encounters an exception, and then one of the catch blocks which follows the try block can handle the exception in some way. and finally block allow us to execute certain code if an exception is thrown or not.

Let's have an simple and easy example to demonstrate that how we need exception handling in C#. This is the simple example to divides two numbers.



/*Example - Why we need Exception Handling - InfoBrother*/

using System;

namespace ExceptionHandling
{
    class Program
    {
        //simple method to divide two numbers:
        public int divide(int x, int y)
        {
            return x / y;
        }


        static void Main(string[] args)
        {
            Program obj = new Program();
            int a, b;
            Console.WriteLine("Enter two Numbers:");

            Console.Write("First Number: ");
            a = Convert.ToInt32(Console.ReadLine());

            Console.Write("Second Number: ");
            b = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("Result: {0} / {1} = {2}", a, b, obj.divide(a, b));

            Console.ReadKey();

        }
    }
}


The above example work perfectly fine, but how about if user enter the value of b zero (0)? as dividing by zero is "IMPOSSIBLE". so if if user will try to divide a number by zero, the compiler will generate this error: DivideByZeroException was unhandled. Now how we can handle this exception, well C# provide us Exception handling tool to handle such type of exception.



  • Exceptions provide a way to transfer control from one part of a Program to Another. C# Exception handling is build upon four keywords: try , catch , finally and throw.

    » try: A try block is used to encapsulate a region of code. If any code throws an exception within that try block, the exception will be handled by the corresponding catch.

    » catch: When an exception occurs, the Catch block of code is executed. This is where we are able to handle the exception, log it, or ignore it.

    » finally: The finally block allow us to execute certain code if an exception is thrown or not. For example, disposing of an object that must be disposed of.

    » throw: The throw keyword is used to actually create a new exception that is the bubbled up to a try catch finally block.



Syntax:

Assuming a block raises an exception, a method catches an exception using a combination of try and catch keyword. a try/catch block is placed around the code that might generate an exception. Code within a try/catch block is referred to as protected code. The basic syntax for using try/catch look like the following:



try
{
    // Throw exception:
}

catch(ExceptionName e1)
{
    // Exception handling code:
}

catch(ExceptionName e2)
{
    // Exception handling code:
}

finally
{
    // Final statement to be executed:
}



We can use exception Class to handle such type of exception. This exception class is exposed by the System.Exception Namespace. All the exception in the .NET Framework are derived from the System.Exception class. Some of the exception classes derived from the System.Exception class are the System.ApplicationException and System.SystemException class. The Following table provides some of the predefined exception classes derived from the System.SystemException class.



Exception ClassDescription
System.IO.IOExceptionHandles Input and Output Errors.
System.IndexOutOfRangeExceptionHandles errors generated when a method refers to an Array index out or range.
System.ArrayTypeMismatchExceptionHandles errors Generated when type is mismatched with the array type.
System.NullReferenceExceptionHandles errors generated from referencing a null object.
System.DivideByZeroExceptionHandles errors generated from dividing a dividend with zero.
System.InvalidCastExceptionHandles errors generated during typecasting.
System.OutOfMemoryExceptionHandles errors generated from insufficient free memory.
System.StackOverFlowExceptionHandles errors generated from stack overflow.


So Using the predefined method, let's try to handle the above example exception.


/*Example -  Exception Handling - InfoBrother*/

using System;

namespace ExceptionHandling
{
    class Program
    {
        //simple method to divide two numbers:
        public int divide(int x, int y)
        {
            if( y == 0) //if Y = 0; 
            {
                //throw Exception:
                throw new System.DivideByZeroException();
            }
            return x / y;
        }


        static void Main(string[] args)
        {
            Program obj = new Program(); //object:

            try  //try this Block:
            {
                int a, b;
                Console.WriteLine("Enter two Numbers:");

                Console.Write("First Number: ");
                a = Convert.ToInt32(Console.ReadLine());

                Console.Write("Second Number: ");
                b = Convert.ToInt32(Console.ReadLine());
                Console.WriteLine("Result: {0} / {1} = {2}", a, b, obj.divide(a, b));
            }

            //if in try block, there is any exception. 
            //will be catched by catch block:
            catch(DivideByZeroException e)
            {
                Console.WriteLine("Attempted divided by Zero: ");
            }

            

            Console.ReadKey();

        }
    }
}


try block must be followed by catch or finally or both blocks. The try block without a catch or finally block will give a compile-time error.

A multiple catch block with the same exception type is not allowed. It will give a compile-time error.
















I Tried my Best to Provide you complete Information regarding this topic in very easy and conceptual way. but still if you have any Problem to understand this topic, or do you have any Questions, Feel Free to Ask Question. i'll do my best to Provide you what you need.

Sardar Omar.
InfoBrother





WRITE FOR INFOBROTHER

Advertising






Advertisement