GETTING A BASE EXCEPTION IN .NET PROGRAMMING
GetBaseException
When you are employed with deeply bedded cipher you haw ingest a ornament for omission direction where a caught omission is enwrapped within additional omission goal and rethrown. Each instance an omission is thrown, additional aggregation haw be additional so that the test omission trainer has sufficiency accumulation to verify the prizewinning state for flowing feat or circumstance logging.
This ornament crapper advance to deeply nested exceptions where the test omission contains the most characteristic accumulation but the initial omission holds whatever aggregation that you require. Handily, the .NET framework’s Exception class, from which every another omission types are derived, includes a method that assists in obtaining the originating exception. The GetBaseException method recursively obtains the InnerException concept until an omission that has no intrinsic omission is found. This is the humble omission that is returned. If the underway omission has no intrinsic exception, it is returned.
To demonstrate, essay streaming the mass code. This simulates a bedded covering by manually creating threesome exceptions, linking them via the InnerException property. The ordinal omission is tangled and caught and its humble omission obtained using the GetBaseException method.
try
{
var exception1 = newborn NullReferenceException("First Exception");
var exception2 = newborn ArgumentNullException("Second Exception", exception1);
var exception3 = newborn InvalidOperationException("Third Exception", exception2);
intercommunicate exception3;
}
catch (Exception ex)
{
var baseException = ex.GetBaseException();
Console.WriteLine(baseException.Message); // "First Exception"
}