Welcome to W3Courses
 Like Us on Facebook

Try Catch Statements for Error Handling in Asp.Net & C#

Error handling in Classic ASP was not the best. ASP.NET has a new error handling mechanism which was already in other languages such as C, C++ and JAVA. It is called the try...catch mechanism, which is also known as "Exception Handling".

This article provides insight about exception handling on the basis of ASP.NET and C# as code behind.

The simple Try statement comes before the block of code, the Catch block of code is where we specify what type of error to look for, and the Finally block of code is always executed and contains cleanup routines and success messages. Since the catch block is specific to the type of error we want to catch, we can use multiple Catch blocks in our Try...Catch...Finally structure.

For example: Try block can contain the statements such as opening the SQL connection and executing the operation. Catch block contains any exceptions that might occur from the executing the operations. Finally block contains cleanup routines and success messages. Following code is an example of executing the mail function to send an email message from an Asp.Net page.

try
{
    SmtpMail.Send(mail);
}
catch(Exception ex)
{
    Response.Write("Exception Occured:   " +ex);
}
finally
{
    Response.Write("Your E-mail has been sent sucessfully");
}

Share