Pages

Saturday, October 1, 2011

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, the following compile time error is reported.
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. The exception is already handled in the ist catch block so it will not check for any other catch block for that. As we already knew that only one catch block is executed at a time.


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.


26 comments:

Anonymous said...

Have you ever thought about adding a little bit more than just your articles?

I mean, what you say is important and all. Nevertheless think of if you
added some great pictures or video clips to give your
posts more, "pop"! Your content is excellent but with pics and video clips, this site could undeniably be one of the greatest in its niche.

Superb blog!

My page; private krankenversicherungen im vergleich
My page - leistungen der krankenversicherung

Anonymous said...

Hello there, I discovered your blog via Google at the same time as searching for a
similar matter, your site came up, it appears to be
like good. I've bookmarked it in my google bookmarks.
Hello there, just become aware of your weblog through Google, and located that it is truly informative. I'm gonna be careful for brussels.
I'll be grateful if you continue this in future. Numerous other people will probably be benefited from your writing. Cheers!

Also visit my web blog ... Versicherungen vergleichen

Anonymous said...

Hi there mates, its fantastic paragraph regarding educationand entirely explained, keep
it up all the time.

my weblog - günstige privatversicherung

Anonymous said...

Hi there, of course this paragraph is genuinely fastidious and I have learned lot of things from it about blogging.
thanks.

Here is my website :: kredit ohne sicherheiten

Anonymous said...

I do consider all the ideas you have presented on your post.
They're very convincing and will certainly work. Nonetheless, the posts are too quick for novices. May just you please prolong them a bit from next time? Thank you for the post.

Check out my webpage; private kv vergleich

Anonymous said...

Attractive section of content. I just stumbled upon your website
and in accession capital to assert that I acquire actually enjoyed
account your blog posts. Any way I'll be subscribing to your augment and even I achievement you access consistently fast.

Have a look at my web blog - best home based business 2011

Anonymous said...

This blog was... how do I say it? Relevant!! Finally I have found something which helped me.
Thank you!

my web blog; Web Hosting Affordable

Anonymous said...

What's up, this weekend is fastidious in support of me, since this moment i am reading this impressive educational paragraph here at my house.

My web blog - residual income business opportunity

Anonymous said...

I used to be recommended this web site by means of my cousin.

I'm now not positive whether this submit is written through him as nobody else recognise such targeted approximately my difficulty. You're amazing!

Thanks!

Feel free to visit my blog :: legit work at home

Anonymous said...

Thanks for another fantastic post. The place else could anyone get that type of info in such a perfect manner of writing?
I've a presentation subsequent week, and I'm on the search for such info.


my weblog best affordable hosting

Anonymous said...

Wonderful article! We are linking to this particularly great
article on our website. Keep up the good writing.


my web site - krankenversicherungen im vergleich

Anonymous said...

Write more, thats all I have to say. Literally, it seems as though you relied
on the video to make your point. You obviously know what youre talking about, why waste your intelligence on just posting
videos to your weblog when you could be giving us
something informative to read?

Here is my blog: web hosting unlimited
Also see my web page > web hosting and domain

Anonymous said...

Hi there colleagues, its enormous piece of writing about cultureand fully defined, keep it
up all the time.

Visit my blog post - kredit ohne schufa sofort

Anonymous said...

With havin so much content and articles do you ever run
into any problems of plagorism or copyright infringement? My blog has a lot of unique content I've either created myself or outsourced but it appears a lot of it is popping it up all over the web without my permission. Do you know any methods to help reduce content from being stolen? I'd
truly appreciate it.

Also visit my web-site - home equity loan with poor credit

Anonymous said...

Very shortly this website will be famous among all blogging viewers, due
to it's nice articles

Check out my weblog :: krankentagegeld pkv

Anonymous said...

I do not even understand how I ended up right
here, but I assumed this submit was good. I don't realize who you're however certainly
you are going to a well-known blogger when you are not already.
Cheers!

Also visit my web blog list of entrepreneur ideas

Anonymous said...

naturally like your web site but you have to test the spelling on
quite a few of your posts. Several of them are rife
with spelling problems and I in finding it very bothersome to tell the
reality nevertheless I will surely come again again.

My web-site; home based business idea
my page > How to Start business

Anonymous said...

Very nice blog post. I definitely love this website.
Keep writing!

Feel free to surf to my webpage; privaten Krankenversicherung

Anonymous said...

Hi there, I enjoy reading all of your article.

I like to write a little comment to support you.


my blog post: affiliate programme
My site > clickbank a scam

Anonymous said...

I was suggested this blog through my cousin. I am now not positive whether this put up
is written through him as no one else understand such unique about my difficulty.
You are incredible! Thanks!

My web blog - krankenkassenvergleich zusatzbeitrag
My website - privatkrankenversicherung vergleich

Anonymous said...

My partner and I absolutely love your blog and find nearly all of your post's to be precisely what I'm
looking for. Does one offer guest writers to write content available for you?
I wouldn't mind writing a post or elaborating on many of the subjects you write related to here. Again, awesome weblog!

Here is my blog; krankengeld private krankenversicherung

Anonymous said...

It is actually a nice and helpful piece of information.
I am glad that you just shared this useful information with us.

Please stay us up to date like this. Thank you for sharing.


Stop by my webpage gesetzliche krankenkassen vergleich
My web site :: Kosten Private Krankenversicherung

Anonymous said...

I am not sure where you're getting your info, but great topic. I needs to spend some time learning more or understanding more. Thanks for great information I was looking for this info for my mission.

Also visit my site outlet fashion
my website :: online schuhe billig

Anonymous said...

Touche. Solid arguments. Keep up the amazing spirit.


my page: legitimate work at home jobs
Also see my web site - jobs for stay at home dads

Anonymous said...

Wow, marvelous blog layout! How long have you been blogging for?

you make blogging look easy. The overall look of your website is magnificent, as well as the content!


Feel free to visit my site ... student pkv
Also see my webpage > vergleich pkv gkv

Anonymous said...

We stumbled over here different page and thought I should
check things out. I like what I see so now i am following you.

Look forward to looking at your web page yet again.


Feel free to visit my web-site http://www.pariscitybreaks.com/wiki/index.php?title=User:SUBJunior