Click here to Skip to main content
15,884,099 members
Articles / Programming Languages / C#

Rethrow exception and InnerException property in .NET

Rate me:
Please Sign up or sign in to vote.
1.40/5 (5 votes)
12 Oct 2010CPOL 28.8K   3   7
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 the original exception.

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

C#
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 the original exception, we have to pass the exception object as a second parameter in addition to friendly message as:

C#
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.


Posted in .NET Technologies, C#/VB.NET, CodeProject, Dot NET Tips Tagged: .NET 3.5, C#, Exception Handling

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead Imfinity India Pte Ltd, Noida (Excelsoft Company)
India India
http://www.imfinity.com/

Comments and Discussions

 
GeneralMy vote of 1 Pin
Vladimir Kniazkov21-Oct-10 21:40
professionalVladimir Kniazkov21-Oct-10 21:40 
GeneralJust use throw; Pin
James Lonero20-Oct-10 12:55
James Lonero20-Oct-10 12:55 
GeneralRe: Just use throw; Pin
Dinesh K Mandal20-Oct-10 19:20
professionalDinesh K Mandal20-Oct-10 19:20 
GeneralMy vote of 1 Pin
Yury Goltsman18-Oct-10 23:45
Yury Goltsman18-Oct-10 23:45 
Below beginner level
GeneralMy vote of 1 Pin
mdarco18-Oct-10 22:51
mdarco18-Oct-10 22:51 
GeneralMy vote of 3 Pin
Emile van Gerwen18-Oct-10 21:43
Emile van Gerwen18-Oct-10 21:43 
GeneralMy vote of 1 Pin
James H18-Oct-10 7:40
James H18-Oct-10 7:40 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.