Labels

Tuesday, March 31, 2009

InnerException Myth

Hi,

 

This is about InnerException.

 

-          When an exception X is thrown as a direct result of a previous exception Y, the InnerException property of X should contain a reference to Y.

-          Use the InnerException property to obtain the set of exceptions that led to the current exception.

-          You can create a new exception that catches an earlier exception. The code that handles the second exception can make use of the additional information from the earlier exception to handle the error more appropriately.

-          Inner Exception is an instance of Exception that describes the error that caused the current exception. The InnerException property returns the same value as was passed into the constructor, or a null reference if the inner exception value was not supplied to the constructor.

-          This property is read-only.

 

Suppose that there is a function that reads a file and formats the data from that file. In this example, as the code tries to read the file, an IOException is thrown. The function catches the IOException and throws a FileNotFoundException. The IOException could be saved in the InnerException property of the FileNotFoundException, enabling the code that catches the FileNotFoundException to examine what causes the initial error. The InnerException property, which holds a reference to the inner exception (IOException), is set upon initialization of the new exception object (FileNotFoundException).

 

 

public class MyAppException : ApplicationException

    {

        public MyAppException(String message) : base(message)

        { }

        public MyAppException(String message, Exception inner) : base(message, inner)

        { }

    }

 

    public class ExceptExample

    {

        private void ThrowInner()

        {

            throw new MyAppException("Inner exception");

        }

 

        public void CatchInner()

        {

            try

            {

                this.ThrowInner();

            }

            catch (Exception e)

            {

                throw new MyAppException("Immediate Exception", e);

            }

        }

    }

 

 

static void Main()

{

            ExceptExample testInstance = new ExceptExample();

 

            try

            {

             testInstance.CatchInner();

            }

            catch (Exception ex)

            {

              MessageBox.Show(ex.Message);             

 MessageBox.Show(ex.Message + " : " + ex.InnerException.Message); 

            }

}

 

Output –

 

Immediate Exception

Immediate Exception : Inner exception

 

 

 

 

Regards,

Arun Manglick

No comments:

Post a Comment