In this post we see how use try-catch-finally block to handle that we suspect code might generate errors. Unless we handle
any exceptions that are raised in our code ourself, they will be caught by the debugger. If we are not running the code within
Visual Web Developer, the exceptions will be caught by the ASP.NET runtime,which displays the errors in the Web Browser.
Additionally,C# enable we to handle runtime errors using the Try-Catch-Finally construct.
The C# syntax looks like this:
try
{
code block…
}
catch (Exception ex)
{
code block…
}
finally
{
code block…
}
As a basic thumb rule for use Try-Catch exception block, we place inside a Try block any code that we suspect
might generate errors that we will want to handle. If an exception is generated, the code in the Catch block will be executed.
We can access information about the error from the ex object, which contains the current
exception—an instance of the Exception class. If the code in the Try block does not generate
any exceptions, the code in the Catch block will not execute. In the end, whether an exception
occurred or not, the code in the Finally block will execute.
C#
try
{
code block…
}
catch (Exception ex)
{
code block…
throw ex;
}
If an error is thrown in the Try block, then we can use the Catch block to optionally execute some code and
then Throw the exception again so that it is caught higher up the stack. We could modify our array example to include
Try and Catch blocks like this:
Code:
protected void Page_Load(object sender, EventArgs e)
{
int[] a = new int[10];
int i;
try
{
for (i = 0; i < 11; i++)
{
a[i] = i;
}
}
catch(Exception ex)
{
messageLabel.Text = "Exception!<br />" + ex.Message;
}
}
In the code above, we can see that the Catch block receives an Exception object,
ex, as a parameter. This object describes the exception that has caused the Catch block to execute.
In our code, we use one of the Exception object's many properties—in this case,
Message—to display some information about the error. In a realistic scenario, we may want to use
this opportunity within the Catch block to possibly redirect a custom error page that will display
a more friendly error message.
In .NET, all exceptions are .NET classes derived from the Exception class. This
means that, in fact, each exception is a different class, but we can treat ex as the generic Exception
class to access the generic details of any error.
The Exception class contains the following properties:
Message : the error message
Source : the name of the exception's source
StackTrace : the names of the methods that were called just before the error occurred
TargetSite : an instance of the MethodBase class that represents the method that caused the error.
No comments:
Post a Comment
Please do not enter any spam link in the comment box.