19 July 2015

Difference between throw and throw ex

Often times you might be wondering what is the difference between 'throw' and 'throw ex' statement when you see the C# code like below:

try
{
 // Do something
}
catch(Exception ex)
{
   // Log it
   throw;
}
And also look at the below code with throw ex:
try
{
 // Do something
}
catch(Exception ex)
{
   // Log it
   throw;
}

The difference is simple.

  • The 'throw' statement throws exception by including the original exception stack-trace
  • where as 'throw ex' statement throws the exception with the stack trace of its line of code execution; 'throw ex' will not include original exception stack-trace.

You can access exception Stack Trace using its string property 'StackTrace'.

Should the difference between 'throw' and 'throw ex' matters?

Yes, it matters. Let's take the below code to understand.

public class UserReposirity
{
 public static string GetUserType
                      (string userName) 
{
   string connectionString = 
   @"Data Source=LOCAL\SQLEXPRESS;Initial Catalog=Users;..;
   string  userType = null;
try
 {
    using (SqlConnection connection = 
          new SqlConnection(connectionString))
    {
      connection.Open();
      using(SqlCommand command = connection.CreateCommand())
      {
        command.CommandText = 
       "
SELECT Type FROM [dbo].[Users1] WHERE UserName=@userName";
       SqlParameter parameter =  command.CreateParameter();
        parameter.ParameterName = "
@userName";
        parameter.SqlDbType = System.Data.SqlDbType.VarChar;
        parameter.Value = userName;
        command.Parameters.Add(parameter);

       object result =  command.ExecuteScalar();
       if (result != null)
        {
         userType = result.ToString();
        }
       }
   }
  }
  catch (Exception ex)
  {
    // Log the exception
         throw;
     // throw ex;
   }

 return userType;
 }
}
class Program
 {
  static void Main(string[] args)
   {
     try
      {
         UserReposirity.GetUserType("ranga");
      }
      catch (Exception ex)
       {
         Console.WriteLine(ex.StackTrace);
       }
   }
 }

The first code snippet is a trivial code, a repository class trying to get the user type for the given user. The method catches the exception, log it and re throw it.

The second code snippet is invoking the repository method. Calling the DB method is wrapped insider a try-catch block. In the catch block its printing the exception stack trace.

StackTrace with 'throw' statement

Now we have set the stage to understand the practical difference between 'throw' and 'throw ex'. Let's run the code AS IS, i.e., by using the throw statement inside the repository method catch block. Let's break the SQL Connection before running the code, so that it will lead to exception. Look at the below stacks trace, it shows the stack trace of the original exception as well.

Original exception StackStrace carried with throw statement

StackTrace with 'throw ex' statement

Now modify the code in the repository method catch block to use the 'throw ex' statement and run the app. This time you will see the below Exception StackTrace. Note, it doesn't include the original exception's StackTrace.

Original exception StackStrace doesn't carried with throw ex statement

Where to use 'throw ex' over 'throw'

When you think exception stacks trace give away confidential information, then use throw ex. Especially when you are writing public repository methods and also when you throwing exceptions from service layer.

You don't want to give away the information about database you are using and the libraries you are using to consumers of your services. Because hackers are around. By looking at the Stack Trace, bad guys will make out certain things, which you may not be comfortable in giving away.

Hope you understood the difference between throw and throw ex and also when to use what over the other. Feel free to comment on the post.

No comments:

Post a Comment