By 22/07/2015 11 Comments

C# Throwing Exceptions Manually

  • Until now the all exceptions were generated/throwing automatically by the run-time system because by default the C# compiler C.L.R throws or generated different types of run-time exceptions automatically.
  • In C# we can throw the different exceptions manually by using a keyword throw.
  • Since all exceptions are built-in in C# and these exceptions are classes which is indirectly derived from its base class which is the Exception class, so an object of an exception class must be created in order to throw it manually by throw clause/keyword. Remember the throw clause must throws an object of that exception and it cannot throw just a type or its reference variable.
  • The built-in exception classes define its different versions of overloaded constructors.
  • When we throw the exception objects then that objects are instance of that exception types or classes.

Example:

using System;
namespace csharpAdvance
{
    class Program
    {
        static void Main(string[] args)
        {
            // try block declaration.
            try
            {
                Console.WriteLine("Before throw clause.");

                // Throw an object of an exception IndexOutOfRangeException manually by “throw” clause.
                throw new IndexOutOfRangeException("IndexOutOfRangeException is thrown manually..!");
            }

            // An IndexOutOfRangeException is being handled by catch statement.
            catch (IndexOutOfRangeException ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.WriteLine("End of try{} and catch{} blocks.");
            Console.ReadKey();
        }
    }
    /*  The Output will be:
     
        Before throw clause.
        IndexOutOfRangeException is thrown manually..!
        End of try{} and catch{} blocks.
     */
}





Next Tutorial →


← 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 .