Try Catch When
This is a feature that's been in VB (.NET) since day one and is very cool. If you've never used it before, what it does is add a condition to your catch statement so the catch is only executed the condition is met. I've never really had much of a use for it, but it's good to know it's there. A couple days ago though, I had a really good use for it though, even though a bit unconventional. My scenario is basically that after a long process a webservice is called to update some things. In the event of a failure, it saves what needs to go up to an xml document to try again later. The "try again later" times are when the application loads or when they click on a certain button. When the application loads, if there was a failed call from before, I want the app to try the call again, but don't do anything if it fails and just move on with loading. When they click the button, I want it to also try the webservice call again, but this time display an exception or message or whatever with what went wrong. Try Catch When is perfect for this. Here's the code:
Public Shared Function SaveChangesToServer(ByVal ShouldThrowException As Boolean) As Boolean
Dim Success As Boolean = False
If GetHasChanges() Then
Try
'Execute WebService Call
Success = True
Catch Ex As Exception When ShouldThrowException
'Clean-up
Throw Ex
Catch
'Clean-up
End Try
End If
Return Success
End Function
Well, I think it's handy anyway...go VB! ;)
UPDATE: Thanks, Steve for pointing out my screw up. Appreciate it! :) Who knows, maybe I have more. Good to know I have readers checking this stuff out though! ;)