Thursday, November 24, 2005

Exceptions are good

I have been playing with FxCop for the past 4 months and I just love it. For those of you who don't know FxCop is a code analysis tool that spots violations of coding standards, i.e. casing of methods, parameters,etc. but it also makes recomendations like when to convert a method to a property, when to make a method static / shared, unused methods / fields, and a whole host of other things. You can get it from

This program recommends that any public method that takes an object be checked to see if the obejct is null and throw an exception if it is.

public sub DoTask(addy as Address)
if addy is nothing then throw new ArgumentNullException("addy")
end sub

I though this was a lot of extra work but the second a null object gets passed to a method I catch it right where it happens instead of further down the call stack where the object might actually be called. Also when I get the exception I know exatly where to look to solve the issue instead of getting an "object reference not set to an instance of an object" exception somewhere in my code.

Another thing that has really helped (and I did not think it would) was writing in methods that I was going to write later (I have a huge select case statement to handle menu item clicks). In a lot of spots I throw NotImplementedExceptions with details of what is not implemented as the argument. Now I quickly see where I have work to do by searching the code (I could use TODO's I know but usually TODO's are for thinks that are partially complete). Also when testing I get that exception and know that I really need to do that chunk of code as it is accessable to the client in the next itteration.

I have also started making my own generic exception classes. Mainly for the different layers to add a bit of distinction between where an exception happened.

<Serializable()> _
Public Class GrowerBusinessException
Inherits Exception

Public Sub New(ByVal message As String)
End Sub

Public Sub New()
End Sub

Public Sub New(ByVal message As String, ByVal innerException As Exception)
MyBase.New(message, innerException)
End Sub

Protected Sub New(ByVal serializationInfo As System.Runtime.Serialization.SerializationInfo, ByVal streamingContext As System.Runtime.Serialization.StreamingContext), streamingContext)
End Sub

End Class

pretty simple? I think so and it is nice to be able to quickly look at a logged exception and spot where the exception happened even by its type.


Post a Comment

<< Home