Follow @RoyOsherove on Twitter

Catch ex As Exception When...

I too would like to add a cool little thingie in VB.Net after reading Rachel's post.

One of the coolest exception handling features (which I could not find in C# BTW) is catching exceptions only on certain conditions. So I can basically write:

Private Sub Button1_Click(By Val sender As System.Object, By Val e As System.Events) Handles Button.Click

Try

'my bad code here 

Catch ex As Exception When false

'we will never get here

End Try

End Sub

How cool is that? And does anyone know the equivalent to this in C#?

Update:

For some reason - some exceptions are never caught by my error handler. Division by zero for example. Take a look at this code:

Try

Dim x As Integer = CInt(Textbooks.Text)

'x is zero

MsgBox(x / x)

Catch ex As Exception

'we never get here!

'whaaa?

Me.Text = ex.Message

End Try

I'm sure it's probably a setting somewhere in VS, but I can't seem to find it. :( Sometimes it's the simplest things that drive you crazy... 

Catch ex As Exception (sometimes)

My new favorite book