Recent Posts

Thursday, August 7, 2008

How can we send cursor to catch even if there is no error in .Net

For error handling put try catch exception in your function and in the catch part you can do all your garbage collection and closing the instances.

And

If your logic doesn't match with certain cases in the function then you can send to catch with the message you want to display to the user by the following way

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim i As Integer
i = Val(Me.txtErrMsg.Text)
Try
If i = 4 Then

' If i = 4 then I want to go to catch and display the message Now throwing exception
Throw New Exception("Exception: 2 is selected")

Else
Me.txtErrMsg.Text = "Normal"

End If

Catch ex As Exception
Me.txtErrMsg.Text = ex.Message
End Try
End Sub

Related Posts by Categories




5 comments:

Colin Angus Mackay said...

The purpose of Try/Catch is to perform login in the event of something exceptional happening. It should NEVER be used for normal program flow control as you seem to be doing here.

Also, the Catch block is not for cleaning up and doing your garbage collection. That is the job of the Finally block. The Finally block will always run regardless of whether an error happened or not.

rprateek said...

Ya you are right but there can be certain cases where we have to throw new exception where our logic doesn't match certain condition.

And also about garbage collection if i don't want to use finally or may be if only i destroy my instances when i get the error then we have to include it in catch .

Thanks for your comment it was helpful.

Colin Angus Mackay said...

But the example in your blog posts is not dealing with exceptional cases. And if you only want to clean up on an error then why not say that.

Exceptions shouldn't be thrown simply because the "logic doesn't match [a] certain condition". They should be thrown because something that you don't expected to happen happens.

Exceptions should only ever deal with exceptional error conditions. Period. No deviation from that rule. A regular error is not cause for using an exception.

For example, if your code opens a file and you are not sure if the file should exist already, that is not exceptional - Check for existance first.

However, If your code is to open a file after the user has used a file dialog to select it, and then some other process deletes the file in the milliseconds between the user clicking Okay and your code opening the file, then that is exceptional and you should throw an exception.

rprateek said...
This comment has been removed by the author.
rprateek said...

We should not throw new Exception() and derive our own Exception class when needed.
But this article is just to let people know about how to throw new exception if they want to use it any way.

Post a Comment