Using The Equivalent Of 'On Error Resume Next' In A Try/Catch

A

Alex Stevens

Hi All.

I have a try catch block which may encouter an error with an empty field:

***** Code Start *****
Try

txtPartNumber.Text = Datarow.Item("PartNumber")
txtPartDescription.Text = Datarow.Item("PartDescription")
txtPartNumber.Text = Datarow.Item("PartNumber")

Catch ex as system.exception

End Try
***** Code End *****

I would like to use something like the old on error resume next, which would
ignore the error and continue with the next line of code.

How would i do this in this example?

One way is to enclose each statement in a try catch itself, but this makes
the code look terrible, whereby it was easy enought pre-,net with the on
error resume next.

Many Thanks

Alex Stevens
 
G

Gabriele G. Ponti

Alex,

You can still use On Error Resume Next in VB.NET, but it's not recommended.
The side effect is that the VB.NET compiler will have to generate a lot of
IL code.

Regards,

Gabriele
 
D

Dmitriy Lapshin [C# / .NET MVP]

Alex,

I'd suggest introducing a simple but "safe" function returning, say, an
empty string, when the field in question is empty. Your code will change to
something like that:

txtPartNumber.Text = SafeQueryItem(Datarow, "PartNumber")
txtPartDescription.Text = SafeQueryItem(Datarow, "PartDescription")
txtPartNumber.Text = SafeQueryItem(Datarow, "PartNumber")

and the SafeQueryItem function will look like:

Private Function SafeQueryItem(ByVal row As DataRow, ByVal itemName As
String)
Try

Return row.Item(itemName)

Catch ex As System.Exception

Return String.Empty

End Try
End Function
 
A

Annie + Pat

You should really use something like:

txtPartNumber.Text = IIf(DataRow.IsNull("PartNumber"), "",
Datarow.Item("PartNumber"))

to allow for the possibility of a NULL field.

--pat
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top