why do we use try catch blocks??
and what is the statement we write in catch's purpose?
Try and Catch I think like in any other high programming languages like java, they are used to execute statement if it is true/correct else it will catch error.
why do we use try catch blocks??
and what is the statement we write in catch's purpose?
Hi Maloov !
In which Language do you need?
OK ! In OOPs, learn exception handling concept.
Try ... for the code to be tested
Catch ... if the test produces any error
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.
[CODE=vb]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[/CODE]
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:
[CODE=vb]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.S endError(ex.Mes sage)
End Try[/CODE]
the call to ErrorHandling.S endError() 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:
[code=vb]
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.S endError(ex.Mes sage)
Finally
MsgBox("This message box will be shown no matter what")
End Try[/CODE]
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.
Comment