Sunday 9 October 2016

Exception, Error Handling Basic in dotnet

Example 1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Exception_Handling
{


    /*
    Error in .net
     * Compilation Error : Error that occurred at the time of compilation. Like, syntax error, invalid object name, invalid variable access.
     * Runtime Error : Error that occurred at runtime, like divide by zero, resource not found etc.
     
    */


    class Program
    {
        static void Main(string[] args)
        {
            int num1 = 0;

            try
            {
                Console.WriteLine("Enter num 1");
                num1 = Convert.ToInt32(Console.ReadLine());
            }
            catch (Exception obj)
            {
                Console.WriteLine("Please enter valid numeric value");
            }
            finally {
                Console.WriteLine("-------------------------------");
            }



            if (num1 != 0)
            {
                Console.WriteLine("Squre of given num is:" + (num1 * num1));
            }
            else {
                Console.WriteLine("Unable to perform operation");
            }



            Console.Read();
        }
    }

}

Example 2
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Exception_Handling_2
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] names = new string[] { "raj", "raja", "ravi" };

            int i = 0;
            try
            {
                Console.WriteLine("Enter index");
                i = Convert.ToInt32(Console.ReadLine());
            }
            catch(Exception excobj) {
                Console.WriteLine("Please Enter valid Index");
            }


            if (i != 0)
            {
                try
                {
                    Console.WriteLine(string.Format("Value at index {0} is {1}", i, names[i]));
                }
                catch
                {
                    Console.WriteLine("Index not found");
                }
            }

           
            Console.Read();

        }
    }
}

Example 3
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Exception_Handling_Null_Ref
{
    class Program
    {
        static string name;
 
        static void Main(string[] args)
        {
            Console.WriteLine(name.ToUpper());
            Console.ReadLine();
        }
    }
}