You can see the code below.
First step, I parse "abc"
to int
. It will raise FormatException
.
In the very first catch
block (that handles the raised FormatException
), I try to open a text file to log the exception message. But this file does not exist so a second exception is raised, this time of type FileNotFoundException
.
I want to store what caused the second exception to be raised, so I add the first exception (fe
of type FormatException
) to the with the fe
parameter (of type FormatException
) passed in the FileNotFoundException(String, Exception)
constructor of the second exception.
That constructor will store the first exception in the InnerException
property of the second exception.
In the outermost 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 innerMessage = "", outerMesage;
if (fnfe.InnerException != null)
innerMessage = fnfe.InnerException.Message; // Inner exception (FormatException) message
outerMesage = fnfe.Message;
Console.WriteLine($"Inner Exception:\n\t{innerMessage}");
Console.WriteLine($"Outer Exception:\n\t{outerMesage}");
}
}
}
Console Output
Inner Exception:
Input string was not in a correct format.
Outer Exception:
NestedExceptionMessage: File `DoesNotExist` not found.
The Inner exception refers to the deeper nested exception that is ultimately thrown. The Outer exception refers the most shallow (in scope) exception.