woensdag 11 maart 2009

Throw ex

No, don't throw your ex anywhere. It's just that a collegue mentioned something I didn't know about re-throwing exceptions in .Net.

Say you want to catch an exception and rethrow it after you're done with it:

    Try
      ' try something
    Catch ex As Exception
      ' do something useful
      Throw / Throw ex
    End Try

There's a difference:
- Throw: ex is rethrown, and stack trace is left intact.
- Throw ex: ex is thrown, but stack trace is erased.

So, generally you want to do Throw, not Throw ex.

C# works the same, although with other syntax of course:

            try
            {
                // try something
            }
            catch (Exception ex)
            {
               // do something useful
               throw; / throw ex;
            }

Also see MSDN for an explanation.

dinsdag 3 maart 2009

Entering string parameters in constructors with Unity

A Microsoft.Practices.Unity container will try to resolve any parameters that a constructor expects. However, for simple string (or int) parameters, that won't work. My example for this was a queue that expects a name parameter:

Public Class Queue
Private mName As String
Public Sub New (name As String)
mName = name
End Sub
End Class

This can be solved, and Microsoft explains how in this section of the documentation.

In this case it results in code like this:

MyContainer.Configure(Of InjectedMembers)() _
.ConfigureInjectionFor(Of Queue)( _
New InjectionConstructor("testqueue"))