Search code examples
asp.netvb.netobout

Try Catch block not catching?


I have a simple function which tries to get a value from an Obout grid filter column, and if the value is empty, ignores it and moves on. For some reason this code ignore my catch block and always shows a System.FormatException when the input string is empty!

More bizarre, if I use visual studio's debugger and set a breakpoint on that line, the catch block functions normally (after I continue from that line). I have already confirmed that my Debug | Exceptions | CLR are not set to catch when thrown. I have also confirmed this same behavior in the production version.

'Get the month selected
    Dim MonthSelected As Integer
    Try
        MonthSelected = CInt(DateCreatedColumn.FilterCriteria.Value)
    Catch ex As Exception
        'If value is empty / not a number reset the filter
        DateCreatedColumn.FilterCriteria.FilterExpression = String.Empty
        Return
    End Try

Solution

  • I think the reason this is happening is because you can't cast a null value to an Int, so the cast fails before the catch has a chance to get the exception.

    Beyond that, I think you need to rewrite this code. It's not a good idea to use an Exception as part of your flow control. Exceptions are computationally expensive and should only be used in exceptional cases. A case you can plan for and program around is, by definition, not exceptional. Use if statements to check for nulls and such, don't use exceptions.