Exception in C#

using System;

namespace @finally
{
    class Program
    {

        static void Main(string[] args)
        {
            try
            {
                int a = 10;
                int b = 0;
                int x = a / b;

            }

            catch (Exception exerror)
            {
               // Console.WriteLine("Error:"+exerror);
                Console.WriteLine("Error: "+exerror.Message);
            }
            
            finally
            {
                Console.WriteLine("Finally block is executed");
            }
            Console.WriteLine("Rest of the code");
            Console.ReadKey();
        }
    }
}

Another example:

User Define Excepton where throws is use

using System;

namespace UserDefinedExeption
{

    public class Temperature
    {
        int temperature = 0;

        public void showTemp()
        {
            if (temperature == 0)
            {
                throw(new TempIsZeroException("Zero temperature found"));
            }
            else
            {
                Console.WriteLine("Temperature: {0}", temperature);
            }
        }
    }

    public class TempIsZeroException : Exception
    {
        public TempIsZeroException(string message) : base(message)
        {
            
        }
    }

    class TestTemperature
    {
        static void Main(string[] args)
        {
            Temperature temp = new Temperature();
            try
            {
                temp.showTemp();
            }
            catch(TempIsZeroException e)
            {
                Console.WriteLine("TempIsZeroException: "+e.Message);
            }
            Console.ReadLine();
        }
    }

}

 

It would be a great help, if you support by sharing :)
Author: zakilive

Leave a Reply

Your email address will not be published. Required fields are marked *