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:
{inMes}");
Console.WriteLine($"Outter Exception:
{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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…