user3736648 user3736648 - 2 months ago 6
C# Question

How to get both exceptions if a child object and a parent object have an exception thrown

In C#, if a child object has try catch block of code, and a parent object also has a try catch block of code, if the child object throws an exception, how can I get the details for both of the exceptions?

Here is the exception class:

public class CompileObjectException : InvalidOperationException
{
private ICustomObject _ownerCustomObject { get; set; }
public ICustomObject OwnerCustomObject
{
get
{
return _ownerCustomObject;
}
set
{
_ownerCustomObject = value;
}
}
public CompileObjectException()
{

}
public CompileObjectException(ICustomObject ownerCustomObject, string message)
: base(message)
{
_ownerCustomObject = ownerCustomObject;
}
}


When the
CompileObjectException
is thrown in both of the objects, the
OwnerCustomObject
is set to the object that the exception is thrown in.

In the above code, I am wanting to get the
OwnerCustomObject
for both the parent and child objects.

Answer

Typically, the parent object will throw the exception with the child exception in the InnerException. InnerExceptions can have InnerExceptions, so you can go all the way down to the root cause.

EDIT:

The pattern looks like:

void SomeMethod()
{
   try
   {
   }
   catch (Exception e)
   {
      throw new MyException(message, e);
   }
}

class MyException : Exception
{
   public MyException(string message, Exception inner)
   : base(message, inner)
   {
   }
}

Obviously there are other details, but that's how you would return both.