Reputation: 4364
I have been searching for some time but could not find any explanation in simple words. I need to know what is for inner exception
in c#.
On msdn, it explains but the example is not quite clear. I need explanation with simple example. thanks
Upvotes: 0
Views: 4728
Reputation: 29207
An inner exception is used to wrap an exception in a new exception. Most of the time you don't need to do this. But suppose you have a class that submits an order. That code calls other classes, and somewhere deep inside it throws a NullReferenceException
.
If you just try to place an order and you get a NullReferenceException
that's rather vague. You might do this:
try
{
SubmitOrder(order);
}
catch(Exception ex)
{
throw new OrderSubmitException("An error occurred while placing the order", ex);
}
Now when the order submit fails what you get isn't just a NullReferenceException
, it's an OrderSubmitException
. When you see that in your log or catch it further up in your application it's easier to tell that it was an exception thrown when placing an order.
But the details, which are really important, are in the InnerException
property of your new exception (because you passed that original exception into the constructor.) So you have an OrderSubmitException
but you also have the more specific details, like the stacktrace, in the InnerException
.
In real life it's not very common that you need to do that. Most of the time when we wrap exceptions like that it's unnecessary. The original exception has its stacktrace and that's good enough.
More often you'll care about the InnerException
when inspecting an exception thrown by something else. Often if the exception doesn't contain enough detail there's more in the InnerException
, and that might also have its own InnerException
.
Upvotes: 2
Reputation: 131
When an exception X is thrown as a direct result of a previous exception Y. Example:
public void ThrowInner ()
{
throw new MyAppException("ExceptExample inner exception");
}
public void CatchInner()
{
try
{
this.ThrowInner();
}
catch (Exception e)
{
throw new MyAppException("Error caused by trying ThrowInner.",e);
}
}
Upvotes: 1
Reputation: 4151
Inner exceptions allow you to NEST exceptions.
var exception1 = new Exception("This is the inner exception");
var exception2 = new Exception("This is the outer exception",exception1);
Upvotes: 1
Reputation: 4423
The InnerException is a property of an exception. When there are series of exceptions, the most current exception can obtain the prior exception in the InnerException property.
See at: http://www.c-sharpcorner.com/uploadfile/puranindia/innerexception-in-C-Sharp/
Upvotes: 3