Saturday, 28 January 2017

INNER EXCEPTIONS IN C#

INNER EXCEPTION


The InnerException property returns the Exception instance that caused the current exception.

To retain the original exception pass it as a parameter to the constructor, of the current exception.

Always check if inner exception is not null before accessing any property of the inner exception object, else, you may get Null Reference Exception.

To get the type of InnerException use GetType() method.
--------------------------------------------------------------------------------------------------------------------------

using System;
using System.IO;

namespace ConsoleApplication4
{
    class Program
    {
        public static void Main()
        {
            try
            {
                try
                {
                    Console.WriteLine("Please enter first number ");
                    int FN = Convert.ToInt32(Console.ReadLine());
                    Console.WriteLine("Please enter second number ");
                    int SN = Convert.ToInt32(Console.ReadLine());

                    int Result = FN / SN;
                    Console.WriteLine("Result = {0}", Result);
                    Console.ReadLine();
                }

                catch (Exception ex)
                {
                    String filePath = @"C:\some\log1.txt";
                    if (File.Exists(filePath))
                    {
                        StreamWriter sw = new StreamWriter(filePath);
                        sw.Write(ex.GetType().Name);
                        sw.Close();
                        Console.WriteLine("Please try later, there is a problem");
                        Console.ReadLine();
                    }
                    else
                    {
                        throw new FileNotFoundException(filePath + "is not present", ex);
                    }
                }

            }
            catch(Exception exception)
            {
                Console.WriteLine("Current Exception ={0} ", exception.GetType().Name);
                if (exception.InnerException != null)
                {
                    Console.WriteLine("Inner Exception = {0} ", exception.InnerException.GetType().Name);
                    Console.ReadLine();
                }
            }
        }
    }

}

No comments:

Post a Comment

Note: only a member of this blog may post a comment.