Monday, 20 August 2018

C#: Inner Exceptions

Inner Exceptions is a property of an exception, it is used to keep track of series of exceptions.

For example, suppose, application throws an exception E1 in try block, the catch block that handles the exception E1 throws Exception E2. Now we need to give these two exceptions E1 & E2 to the user to better understand the problem.

How to pass Inner Exception?
By passing the exception as an argument to the constructor, you can pass inner exception.

        try
        {
            throw new ArrayTypeMismatchException("Array type mismatch Exception");
        }
        catch (ArrayTypeMismatchException e)
        {
            throw new ArithmeticException("Arithmetic Exception", e);
        }

Notify above snippet, 'ArithmeticException' takes 'ArrayTypeMismatchException' as an argument.

How to access Inner Exception?
By using 'InnerException' property, you can access the inner exception.
    
          if (e.InnerException != null)
     {
         Console.WriteLine("\n**************************\n");
        Console.WriteLine("Inner Exception");
        Console.WriteLine(String.Concat(e.InnerException.StackTrace, e.InnerException.Message));
     }

Following is the complete working example.

Program.cs
using System;

class Program
{
    public static void method1()
    {
        try
        {
            throw new ArrayTypeMismatchException("Array type mismatch Exception");
        }
        catch (ArrayTypeMismatchException e)
        {
            throw new ArithmeticException("Arithmetic Exception", e);
        }

    }

    static void Main(string[] args)
    {
        try
        {
            method1();
        }
        catch(Exception e)
        {
            Console.WriteLine(String.Concat(e.StackTrace, e.Message));

            if (e.InnerException != null)
            {
                Console.WriteLine("\n**************************\n");
                Console.WriteLine("Inner Exception");
                Console.WriteLine(String.Concat(e.InnerException.StackTrace, e.InnerException.Message));
            }

        }
        
    }
}


Run above application, you can able to see following output.
  at Program.method1() in C:\Users\Krishna\Documents\Visual Studio 2015\Projects\HelloWorld\HelloWorld\Program.cs:line 13
   at Program.Main(String[] args) in C:\Users\Krishna\Documents\Visual Studio 2015\Projects\HelloWorld\HelloWorld\Program.cs:line 22Arithmetic Exception

**************************

Inner Exception
   at Program.method1() in C:\Users\Krishna\Documents\Visual Studio 2015\Projects\HelloWorld\HelloWorld\Program.cs:line 9Array type mismatch Exception




Previous                                                 Next                                                 Home

No comments:

Post a Comment