What is inner Exception

前端 未结 3 2063
梦如初夏
梦如初夏 2020-12-05 07:19

I have read the MSDN but, I could not understand this concept.

Correct me if I am wrong,

A innerexception will be used in hand with current ex

3条回答
  •  抹茶落季
    2020-12-05 07:50

    You can see the code below.

    First step, I parse "abc" to integer. It will raise FormatException.

    In the catch block, I try to open a text file to log the exception message. But this file didn't exist. FileNotFoundException will be raised.

    I want to know what raised the second exception, so I add the first exception (or FormatException) to the constructor of the second exception.

    Now the first exception is InnerException of the second exception.

    In the catch block, I can access InnerException's properties to know what the first exception is.

    Is it useful?

    using System;
    using System.IO;
    public class Program
    {
        public static void Main( )
        {
            try
            {
                try
                {
                    var num = int.Parse("abc"); // Throws FormatException               
                }
                catch ( FormatException fe )
                {
                    try
                    {
                        var openLog = File.Open("DoesNotExist", FileMode.Open);
                    }
                    catch
                    {
                        throw new FileNotFoundException("NestedExceptionMessage: File `DoesNotExist` not found.", fe );
                    }                              
                }
            }
            // Consider what exception is thrown: FormatException or FileNotFoundException?
            catch ( FormatException fe)
            {
                // FormatException isn't caught because it's stored "inside" the FileNotFoundException
            }
            catch ( FileNotFoundException fnfe ) 
            {
                string inMes="", outMes;
                if (fnfe.InnerException != null)
                    inMes = fnfe.InnerException.Message; // Inner exception (FormatException) message
                outMes = fnfe.Message;
                Console.WriteLine($"Inner Exception:\n\t{inMes}");
                Console.WriteLine($"Outter Exception:\n\t{outMes}");
            }        
        }
    }
    

    Console Output

    Inner Exception:
        Input string was not in a correct format.
    Outter Exception:
        NestedExceptionMessage: File `DoesNotExist` not found.
    

    The Outter exception refers to the most deeply nested exception that is ultimately thrown. The Inner exception refers the most shallow (in scope) exception.

提交回复
热议问题