By 22/07/2015 12 Comments

C# Catch All Exceptions

  • In C# all types of exceptions can be caught at once by defining a catch block without specifying any exception type and exception reference variable, that catch block is called as catch-all.
  • Remember the catch-all block must be defined last in other catch blocks.

Example:

using System;
namespace csharpBasic
{
    class ExceptionExample
    {
        // An int type array.
        int[] Numbers = { 1, 2 };

        // A void type method.
        public void Devision(int number, int devidedBy)
        {
            Console.WriteLine("Division " + number + "/" + devidedBy + " = " + (number / devidedBy));
        }

        // void type method GetArray().
        public void GetArray()
        {
            // for loop loops through each int number and assigns into an array.
            for (int count = 0; count < 4; count++)
            {
                Numbers[count] = count;
                Console.WriteLine(Numbers[count]);
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            ExceptionExample exceptionExample = new ExceptionExample();

            try
            {
                // Division() and GetArray() method is called inside the try block.
                exceptionExample.GetArray();
                exceptionExample.Devision(10, 0);
            }

           // A single catch block which will handle all types of exceptions.
            catch
            {
                Console.WriteLine("All exceptions has been caught!");
            }

            finally
            {
                Console.WriteLine("finally{} block is executed.");
            }
            Console.ReadKey();
        }
    }
    /*  The Output will be:
     
        0
        1
        All exceptions has been caught!
        finally{} block is executed.
     */
}






← Previous Tutorial


Posted in: C# Advance, C#.NET

Leave your valuable Comment

Have a natural attraction for women cosmetics and replica watches uk clothes, no
more than two for men the most attractive one, is to make their own driving experience, happy and can serve as the facade of the car, another is to highlight the taste edify sentiment rolex replica watch. The replica rolex is undoubtedly the most fashionable accessories, wear a suit to attend the activities, but also get a decent match on the replica watches .