What are Exceptions?
Exceptions are unusual occurrences that happen within the logic of an application.
What are the 3 approaches to handle exceptions in a Web application?
1. Use exception-handling structures to deal with exceptions within the scope of a procedure. This technique is called structured exception handling (SEH) in the Visual Studio .NET documentation.
try
catch
finally
2. Use error events to deal with exceptions within the scope of an object.
Page_Error
Global_Error
Application_Error
3. Use custom error pages to display informational messages for unhandled exceptions within the scope of a Web application.
Where will the control flow if an exception occurs inside a try block?
If a statement in a try block causes an exception, control flow passes immediately to the next catch statement. When control flow passes to a catch block, the statements contained in the catch block are processed to correct the error or otherwise handle the exception.
Will the finally block gets executed, if an exception occurs?
Yes, a finally block will always be executed irrespective of whether an exception has occured or not.
What is the main use of a finally block in exception handling?
Finally block is mainly used to free resources used within the try block.
How do you raise an exception?
Use the throw keyword to raise an exception. Use this keyword within your exception-handling structure to immediately pass control flow to the catch statement.
Will the following code block compile?
try
{
throw new System.IO.FileNotFoundException();
}
catch (Exception E)
{
Response.Write(E.Message);
}
catch (System.IO.FileNotFoundException FNFE)
{
Response.Write(FNFE.Message);
}
No, a compile time error A previous catch clause already catches all exceptions of this or of a super type ('System.Exception').
Catch blocks are evaluated in the order in which they appear in code. The exception declaration of each catch block determines which type of exception the catch block handles. Always order catch blocks from most specific to most general. So, in the preceding sample, FileNotFoundException should be placed before the general Exception catch block.
What is ApplicationException class used for?
If you are creating a large application or creating components that are used by other applications, you might want to define your own exception classes based on the ApplicationException class. For example, the following code defines a class for the UserLoggedOnException:
public class UserLoggedOnException : System.ApplicationException
{
// Exception constructor (overloaded).
public UserLoggedOnException()
: this("The user is already logged on to the server", null)
{
}
public UserLoggedOnException(string message)
: this(message, null)
{
}
public UserLoggedOnException(string message, Exception inner)
: base(message, inner)
{
}
}
The preceding UserLoggedOnException class inherits its properties and methods from the ApplicationException base class. The new exception class provides only its own constructor to set the default message to display. This is a standard practice.
What are Error Events?
Another way to handle exceptions is through the Web objects’ built-in error events. When an unhandled exception occurs in a Web application, ASP.NET fires the error events shown below.
Page_Error : Occurs when an unhandled exception occurs on the page. This event procedure resides in the Web form.
Global_Error : Occurs when an unhandled exception occurs in the application. This event procedure resides in the Global.asax file.
Application_Error : Occurs when an unhandled exception occurs in the application. This event procedure resides in the Global.asax file.
Error events let you handle exceptions for an entire object in a single, centralized location—the error event procedure. This is different from using exception-handling structures, in which exceptions are handled within the procedure where they occurred. You can use error events in the following ways:
As a substitute for exception-handling structures :
Because error events occur outside the scope of the procedure in which the error occurred, you have less information about the steps leading up to the exception and therefore less ability to correct the exception condition for the user. However, using exception-handling events is fine for tasks where you might not be able to correct the exception in code.
As an adjunct to exception-handling structures :
Error events can provide a centralized “backstop” against exceptions that were not foreseen or handled elsewhere. Using the two exception-handling techniques together lets you catch all exceptions before the user sees them, display a reasonable message, and even record the exception in a log as part of an ongoing effort to improve your application.
Give an example to show how error events can be used to handle exceptions?
To handle an exception using error events, follow these steps:
1. In the Page_Error event procedure, get the exception that occurred using the GetLastError method.
2. Do something with the exception, such as display a message to the user, take steps to correct the problem, or write to an error log.
3. Clear the exception using the ClearError method.
4. Redisplay the page. Web form processing stops immediately when an exception occurs, so server controls and other items on the page might not be displayed after the exception is cleared.
5. Add the following code to Page_Error event procedure on the web page.
private void Page_Error(object sender, System.EventArgs e)
{
// Get the error.
Exception ex = Server.GetLastError();
// Store the message in a session object.
Session["Error"] = ex.Message;
// Clear the error message.
Server.ClearError();
// Redisplay this page.
Server.Transfer("ErrorEvents.aspx");
}
The preceding code stores the exception message as a Session state variable before clearing the exception so that the message can be displayed when the page is reloaded by the Transfer method. The following code displays the saved exception message when the page is redisplayed:
Add the following code to Page_Load event procedure on the web page.
private void Page_Load(object sender, System.EventArgs e)
{
// Display error. if any.
if (Session["Error"] != null)
{
litError.Text = "The following error occurred:
" +
Session["Error"].ToString();
// Clear the Session state variable.
Session["Error"] = null;
}
}
Can you have a try block without a catch or a finally block?
No, you cannot have a try block without a catch or a finally block. A try block cannot exist in isolation. A try block should be followed by either a catch block or a finally block or both.
Is the following code legal?
try
{
Response.Write("Try block executed");
}
finally
{
Response.Write("Finally block executed");
}
Yes, it's legal. A try statement does not have to have a catch statement if it has a finally statement.
What is wrong with using the following type of exception handler?
catch(Exception E)
{
//Some Code
}
This handler catches exceptions of type Exception, therefore, it catches any exception. This can be a poor implementation because you are losing valuable information about the type of exception being thrown and making your code less efficient. As a result, your program may be forced to determine the type of exception before it can decide on the best recovery strategy.
Will the second catch block handle the exception thrown by the first catch block?
try
{
throw new System.IO.FileNotFoundException();
}
catch (System.IO.FileNotFoundException FNFE)
{
Response.Write(FNFE.Message);
throw new Exception();
}
catch(Exception E)
{
Response.Write(E.Message);
}
No. For a catch block to handle the exception, the statement that raised the exception must be inside a try block.
What will happen to the exception raised by the code in the following Button1_Click event procedure?
protected void Button1_Click(object sender, EventArgs e)
{
throw new Exception();
try
{
Response.Write("Hello");
}
catch (Exception E)
{
Response.Write(E.Message);
}
}
The exception will not be handled by the catch block because the statement that raised the exception must be inside a try block.
01 July, 2009
ASP.NET Events related Interview Questions
What are the different levels at which events can occur in an ASP.NET web application?
Web application events occur at the application, page, and server control levels
Give some examples for application level events?
1. Application_Start
Occurs when the first user visits a page within your Web application.
2. Application_End
Occurs when there are no more users of the application.
3. Application_BeginRequest
Occurs when at the beginning of each request to the server. A request happens every time a browser navigates to any of the pages in the application.
4. Application_EndRequest
Occurs when at the end of each request to the server.
5. Session_Start
Occurs when a new user visits a page within your application.
6. Session_End
Occurs when a user stops requesting pages from the Web application and their session times out. Sessions time out after a period specified in the Web.config file.
7. Application_Error
Occurs when when there is an unhandled exception in an application.
Where are the application level event handlers present in an ASP.NET web application?
Application level event handlers are present in Global.asax of an ASP.NET web application
What is the difference between Application and Session Events?
At an application level we can have Application and Session events. Use Application events to initialize objects and data that you want to make available to all the current sessions of your Web application. Use Session events to initialize data that you want to keep throughout individual sessions, but that you don’t want to share between sessions.
Give an example of how to use Application and Session events?
To see how Application and Session events occur, add the following code to the Global.asax file in a Web forms project.
void Application_Start(object sender, EventArgs e)
{
// Create Application state variables.
Application["AppCount"] = 0;
Application["SessCount"] = 0;
// Record application start.
Application["AppCount"] = (int)Application["AppCount"] + 1;
}
void Session_Start(object sender, EventArgs e)
{
// Count sessions.
Application["SessCount"] = (int)Application["SessCount"] + 1;
}
void Session_End(object sender, EventArgs e)
{
// Decrement sessions.
Application["SessCount"] = (int)Application["SessCount"] - 1;
}
Add the following code to WebForm1.aspx file in a Web forms project and set WebForm1 as start up page.
protected void Page_Load(object sender, EventArgs e)
{
// Display Application count.
Response.Write("Number of applications: " +
Application["AppCount"] + "
");
// Display session count.
Response.Write("Number of sessions: " +
Application["SessCount"] + "
");
}
To demonstrate the events, run the preceding code, and then start a new instance of the browser and navigate to the address. Each new instance of the browser increments the session count, but the application count stays at 1.
How long a webform instance is available on the web server?
Web forms live for barely a moment. When we request a webform from the browser, the applications executable creates an instance of the requested Web form, generates the HTML to respond to the request, and posts that response to the browser. It then destroys the instance of the Web form.
When the client browser has the generated HTML, the user can type text in boxes, select options, and perform other tasks until triggering a postback event, such as a button click. Postback events cause the browser to send the page’s data (view state) back to the server for event processing. When the server receives the view state, it creates a new instance of the Web form, fills in the data from the view state, and processes any events that occurred. As soon as the server has finished, it posts the resulting HTML back to the browser and destroys the instance of the Web form.
Give some examples for page level events and when they occur?
1. Page_Init
During Page_Init the server controls are loaded and initialized from the Web form’s view state. This is the first step in a Web form’s life cycle.
2. Page_Load
During Page_Load the server controls are loaded in the Page object. View state information is available at this point, so this is where you put code to change control settings or display text on the page.
3. Page_PreRender
During Page_PreRender the application is about to render the Page object.
4. Page_Unload
During Page_Unload the page is unloaded from memory.
5. Page_Disposed
During Page_Disposed the Page object is released from memory. This is the last event in the life of a Page object.
6. Page_Error
Page_Error event is raised when an unhandled exception occurs.
7. Page_AbortTransaction
Page_AbortTransaction is raised when a transaction is aborted.
8. Page_CommitTransaction
Page_CommitTransaction is raised when a transaction is commited.
9. Page_DataBinding
Page_DataBinding occurs when a server control on the page binds to a data source.
What is the order in which Page level events occur?
Page_Init
Page_Load
Page_PreRender
Page_Unload
Page_Disposed
What page property is used to differentiate between a postback and initial get request of a page?
IsPostback property of the Page class.
What are the 3 types of Server Control Events?
Server controls, such as a Button, TextBox, and DropDownList, each have their own sets of events that occur in response to user actions. However, not all server control events are created equal. There are three types of server control events as listed below.
Postback events :
These events cause the Web page to be sent back to the server for immediate processing. Postback events affect perceived performance because they trigger a round-trip to the server. A Button control triggers a postback event. A dropdowinlist can also trigger a post back if the AutoPostBack property of the DropDownList is set to true, else a dropdownlist triggers a cached event. The same is the case with a TextBox.
Cached events :
These events are saved in the page’s view state to be processed when a postback event occurs. A DropDownList and a TextBox can trigger a cached event if the AutoPostBack property is set to false.
Validation events :
These events are handled on the page without posting back or caching. The validation server controls use these types of events.
How can you convert a Cached event of control to a post back event?
You can convert a Cached event of control to a post back event by setting the AutoPostBack property to true.
What is the order in which events are executed?
The validations controls are evaluated before the page is posted back to the server. When the page is posted back, the Page_Init and Page_Load events are handled, then cached events are handled, and finally the event that caused the postback is processed. Among cached events, the event order is determined by the order of the controls on the Web form.
Subscribe to:
Posts (Atom)