Exception:
An exception is unexpected error or problem.
Exception Handling:
Method to handle error and solution to recover from it, so that program works smoothly.
Try Block:
-> Try Block consist of code that might generate error.
-> Try Block must be associated with one or more catch block or by finally block.
-> Try Block need not necessarily have a catch Block associated with it but in that case it must have a finally Block associate with it.
Catch Block:
-> Catch Block is used to recover from error generated in try Block.
-> In case of multiple catch Block, only the first matching catch Block is executed.
-> When you write multiple catch block you need to arrange them from specific exception type to more generic type.
-> When no matching catch block are able to handle exception, the default behavior of web page is to terminate the processing of the web page.
Finally Block:
-> Finally Block contains the code that always executes, whether or not any exception occurs.
-> When to use finally Block? - You should use finally block to write cleanup code. i.e. you can write code to close files, database connections, etc.
-> Only One finally block is associated with try block.
-> Finally block must appear after all the catch block.
-> If there is a transfer control statement such as goto, break or continue in either try or catch block the transfer happens only after the code in the finally block is executed.
-> If you use transfer control statement in finally block, you will receive compile time error.
Throw Statement:
-> A throw statement is used to generate exception explicitly.
-> Avoid using throw statement as it degrades the speed.
-> Throw statement is generally used in recording error in event log or sending an email notification about the error.
Using Statement:
-> Using statement is used similar to finally block i.e. to dispose the object.
-> Using statement declares that you are using a disposable object for a short period of time. As soon as the using block ends, the CLR release the corresponding object immediately by calling its dispose() method
Is it a best practice to handle every error?
-> No, it is not best practice to handle every error. It degrades the performance.
-> You should use Error Handling in any of following situation otherwise try to avoid it.
-> If you can able to recover error in the catch block
-> To write clean-up code that must execute even if an exception occur
-> To record the exception in event log or sending email.
Difference between catch(Exception ex) and catch:
try
{
}
catch(Exception ex)
{
//Catches all cls-compliant exceptions
}
catch
{
//Catches all other exception including the non-cls compliant exceptions.
}
Managing Unhandled Exception:
You can manage unhandled exception with custom error pages in asp.net. You should configure the
Mode Attribute: It specifies how custom error page should be displayed. It contains 3 values.
On - Displays custom error pages at both the local and remote client.
Off - Disables custom error pages at both the local and remote client.
RemoteOnly - Displays custom error pages only at the remote client, for local machine it displays default asp.net error page. This is default setting in web.config file.
DefaultRedirect: It is an optional attribute to specify the custom error page to be displayed when an error occurs.
You can display custom error page based on http error statusCode using error element inside the customeError element, in case the no specific statusCode match it will redirect to defaultRedirect page.
< customErrors mode="RemoteOnly" defaultRedirect="~/DefaultErrorPage.htm" >
< error statusCode="403" redirect="NoAccess.htm" />
< error statusCode="404" redirect="FileNotFound.htm" />
</customErrors >
Events fired on Unhandled Exception
Two events fire in successive order on unhandled exception
Page.Error() Event - Performing error handling at page level.
Application.Error() Event - Performing error handling at application level.
Page.Error() Event
Lets display error message for divide by error instead of display custom error page.
Add the Page_Error() Event
protected void Page_Error(object sender, EventArgs e)
{
Response.Write("Error: " + Server.GetLastError().Message + "");
Server.ClearError();
}
Server.GetLastError() method is used to display last error, while Server.ClearError() will clear the last exception and does not fire the subsequent error events. For this reason, you will notice that custom error page is not displayed even though there is unhandled error, and a default error message is displayed.
Application.Error() Event
Application.Error Event is used to handle unhandled exception of entire application. This event lies in Global.asax file. You can use this event to send email for error or generate a text file or recording error information in database, etc.
Here we will generate a text file in MyError directory of application and send email of same error to web master.
So lets begin by adding namespace to global.asax
For adding namespace to global.asax make use of import statement.
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Net" %>
<%@ Import Namespace="System.Net.Mail" %>
Now, add following code to Application_Error Event in Global.asax for generating error text file and sending error reporting email to webmaster in asp.net
void Application_Error(object sender, EventArgs e)
{
Exception err = (Exception)Server.GetLastError().InnerException;
//Create a text file containing error details
string strFileName = "Err_dt_" + DateTime.Now.Month + "_" + DateTime.Now.Day
+ "_" + DateTime.Now.Year + "_Time_" + DateTime.Now.Hour + "_" +
DateTime.Now.Minute + "_" + DateTime.Now.Second + "_"
+ DateTime.Now.Millisecond + ".txt";
strFileName = Server.MapPath("~") + "\\MyError\\" + strFileName;
FileStream fsOut = File.Create(strFileName);
StreamWriter sw = new StreamWriter(fsOut);
//Log the error details
string errorText = "Error Message: " + err.Message + sw.NewLine;
errorText = errorText + "Stack Trace: " + err.StackTrace + sw.NewLine;
sw.WriteLine(errorText);
sw.Flush();
sw.Close();
fsOut.Close();
//Send an Email to Web Master
//Create Mail Message Object with content that you want to send with mail.
MailMessage MyMailMessage = new MailMessage ("dotnetguts@gmail.com","vivek_on_chat@yahoo.com",
"Exception:" + err.Message, errorText);
MyMailMessage.IsBodyHtml = false;
//Proper Authentication Details need to be passed when sending email from gmail
NetworkCredential mailAuthentication = new
NetworkCredential("dotnetguts@gmail.com", "password");
//Smtp Mail server of Gmail is "smpt.gmail.com" and it uses port no. 587
//For different server like yahoo this details changes and you can
//get it from respective server.
SmtpClient mailClient = new SmtpClient("smtp.gmail.com",587);
//Enable SSL
mailClient.EnableSsl = true;
mailClient.UseDefaultCredentials = false;
mailClient.Credentials = mailAuthentication;
mailClient.Send(MyMailMessage);
}
On running the program and generating exception will create error file in MyError directory and will send email stating error to web master, And it will display custom error page to user
No comments:
Post a Comment