Inner Exception in C#

Inner Exception in C# with an Example

In this article, I am going to discuss the Inner Exception in C# with an example. Please read our previous article before proceeding to this article where we discussed how to create a Custom Exception in C# with examples.

What is Inner Exception in C#?

The Inner Exception in C# is a property of an exception class. When there is a series of exceptions, then the most current exception obtains the previous exception details in the InnerException property. In order words, we can say that the InnerException property returns the original exception that caused the current exception. If this is not clear at the moment, then don’t worry we will discuss this with examples.

Inner Exception Example in C#:

Let us say we have an exception inside a try block which is throwing DivideByZeroException and the catch block catches that exception and then tries to write that exception it to a file. However, if the file path is not found, then the catch block is also going to throw FileNotFoundException.

Let’s say the outside try block catches this FileNotFoundException exception, but how about the actual DivideByZeroException that was thrown? Is it lost? No, the InnerException property of the Exception class contains the actual exception. 

Example:

Let us understand the Inner Exception with an example. In order to see the inner exception, we have to make this program cause an exception to fail. To do that we have 3 options

  1. Enter a Character instead of a number (Causes Format Exception)
  2. Or Enter a very big number that an integer cannot hold (Causes Over Flow Exception)
  3. Or Enter Zero for Second Number (Causes Divide By Zero Exception)
using System;
using System.IO;
namespace ExceptionHandlingDemo
{
    class Program
    {
        public static void Main()
        {
            try
            {
                try
                {
                    //throw new ArgumentException();
                    Console.WriteLine("Enter First Number");
                    int FN = Convert.ToInt32(Console.ReadLine());

                    Console.WriteLine("Enter Second Number");
                    int SN = Convert.ToInt32(Console.ReadLine());

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

                catch (Exception ex)
                {
                    //make sure this path does not exist
                    string filePath = @"C:\LogFile\Log.txt";
                    if (File.Exists(filePath))
                    {
                        StreamWriter sw = new StreamWriter(filePath);
                        sw.Write(ex.GetType().Name + ex.Message + ex.StackTrace);
                        sw.Close();
                        Console.WriteLine("There is a problem! Plese try later");
                    }
                    else
                    {
                        //To retain the original exception pass it as a parameter
                        //to the constructor, of the current exception
                        throw new FileNotFoundException(filePath + " Does not Exist", ex);
                    }
                }
            }

            catch (Exception e)
            {
                //e.Message will give the current exception message
                Console.WriteLine("Current or Outer Exception = " + e.Message);

                //Check if inner exception is not null before accessing Message property
                //else, you may get Null Reference Excception
                if (e.InnerException != null)
                {
                    Console.Write("Inner Exception : ");
                    Console.WriteLine(String.Concat(e.InnerException.StackTrace, e.InnerException.Message));
                }
            }
            Console.ReadLine();
        }
    }
}

When you run the above program it will give us the following output.

Inner Exception in C#

In the next article, I will discuss the Exception Handling Abuse in C#. Here, in this article, I try to explain the Inner Exception in C# step by step with one example. I would like to have your feedback. Please post your feedback, question, or comments about this article.

1 thought on “Inner Exception in C#”

Leave a Reply

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