Sunday, May 10, 2009

Interview Questions on ASP.NET Exception Handling

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.

No comments:

Post a Comment