why do we use try catch blocks??
and what is the statement we write in catch's purpose?
as the others have stated, you use try...catch to catch errors.
- Try
-
' any code that might generate an error here, for example connecting to a database
-
Catch ex As Exception
-
' react to the error here. in this example, I want to throw the error
-
Throw ex
-
End Try
if you use the above code, it differs little from just running the code without try...catch. but if you change the code in the catch statement you can handle the error much more smoothly.
in an asp.net web application i wrote some time ago, i created a public class called ErrorHandling, in which there was a subroutine that emailed the error message to the administrator of the website. I won't show you the whole class, but everywhere i used code that could potentially cause an error, i put it within a try...catch block as follows:
- Try
-
' any code that might generate an error here, for example connecting to a database
-
Catch ex As Exception
-
' send an email to the administrator of the site.
-
ErrorHandling.SendError(ex.Message)
-
End Try
the call to ErrorHandling.SendError() is a custom call to a class that I created myself - it won't work for you unless you create a class also.
another thing that has not been mentioned in this thread is the third, optional, part of the try...catch statement: finally. it is really simple to understand - it just means that the code in that block will be run regardless of whether an error occurs. an example might show what i mean:
-
Try
-
' any code that might generate an error here, for example connecting to a database
-
Catch ex As Exception
-
' send an email to the administrator of the site.
-
ErrorHandling.SendError(ex.Message)
-
Finally
-
MsgBox("This message box will be shown no matter what")
-
End Try
i hope this gives you a picture of how try...catch can be used to handle errors smoothly improve the user experience of an application.