April 11 01
Vb.Net Error catching
—
Jonathan
So if you have ever programmed for longer than well about 5 seconds you have probably run into an error. So what to do with the errors? I found out about this fantastic little trick for error handling in VB.Net that helped me with a SaaS project I'm working on.
As most dynamic projects go I needed to pass information from a text box into SQL statement (Linq2SQL, stored proc). Again, as most dynamic projects go I knew that I would need to valid what went into the text box before using it. In this case I need to verify that
1) the text box actually had something in it, if not set it to zero,
if TbSomething.text = "" then TbSomething.text = 0
2) verify that what was in the textbox was a number and 3) that it was a positive number.
Try
i = CInt(TbSomething.Text)
If i < 0 Then Throw New Exception("Negative Number")
Catch ex As InvalidCastException
errormsg += "Must be a number<br/>"
Catch ex As Exception When ex.Message = "Negative Number"
errormsg += "Must be a positive number<br/><br/>"
End Try
master.errormsg = errormsg
The interesting part of this was the When clause. When using Catch and an Exception type is not enough or you are using a custom Exception you can use the When clause to additional conditions. Then When clause could execute a method or be a simple comparison as above. Another example was using it to allow the application to retry an operation and finally give up if a condition was true thus allowing the Catch When to fire.
Once the error(s) where caught I used the error display method I wrote about in this post
761087b7-dee8-400c-8902-348606cf34b4|0|.0
Tags: .net 4.0, Vb.Net, error handling, catch, error catch, catch when, exceptions |
Categories: