Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Data items to exception but not calling throw ex

I have extended NLog to log all items in the Exception.Data collection. So, when I catch an SqlException, in my data access code, I like to add a few items to the Exception.Data dictionary to provide better logging. I don't always want to log from within the catch, but instead, let the exception bubble up and be handled later. So I write something like this:

Try
   ...
Catch exception As Exception
   exception.Data.Add("SP", StoreProcedureNameCost)
   exception.Data.Add("Connection", myConnection.ConnectionString)
   Throw
End Try

Does calling just Throw instead of Throw exception still have have all of my added Data items?

like image 571
slolife Avatar asked Dec 04 '25 17:12

slolife


2 Answers

Yes, It will preserve the changes made to Data property. The fundamental difference between throw and throw ex is that the stack trace does not change with calling throw whereas it gets changed with throw ex.

like image 161
jags Avatar answered Dec 06 '25 08:12

jags


I gave it a try myself and it works like I hoped. Just calling throw DOES preserve new data added to the exception:

Try
   Try
      Throw New NotImplementedException("Hi")
   Catch ex As Exception
      ex.Data.Add("Here", "It is there")
      Throw
   End Try
Catch ex As Exception
   Dim msg As String = ex.Data("Here").ToString()
   Response.Write(msg)
End Try

It worked and spit out "It is there".

like image 34
slolife Avatar answered Dec 06 '25 07:12

slolife



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!