Home > .Net Technologies, C#/VB.Net, CodeProject, Dot Net Tips > Rethrow exception and InnerException property in .Net

Rethrow exception and InnerException property in .Net

Most of the time when we re-throw exception from our code block, we supply some meaningful and friendly message if any error condition occurs. This message is supplied in the constructor method of that exception type. But in this re-throwing process, we often forget to preserve Inner Exception property. And when we log the exception message (ex.Message), we lose the details of original exception.

In the example below, we have re-thrown exception with only friendly message in the constructor method.

private void DivideOperation()
{
try
{
int x = 5;
int y = 0;
int result = x/y;
}
catch (Exception ex)
{
throw new DivideByZeroException(“Invalid operands were given.”);
}
}

Null InnerException
Fig 1: InnerException property is null.

This is of course not a good practice to do exception handling. So to preserve the details of original exception, we have to pass the exception object as second parameter in additional to friendly message as:

private void DivideOperation()
{
try
{
int x = 5;
int y = 0;
int result = x/y;
}
catch (Exception ex)
{
throw new DivideByZeroException(“Invalid operands were given.”, ex);
}
}

Valid inner exception
Fig 2: InnerException property detail is preserved.

One can see the difference of InnerException property value in these two cases.

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: