C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Reviews   Communities   Interview   Jobs   Projects   Training   Your Ad Here    
Silverlight Games | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Polls | Revenue Sharing | Lobby | Gift Shop |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...






Resources » Articles » .NET Framework »

Exceptional Handling at all Levels


Posted Date: 29 Nov 2005    Resource Type: Articles    Category: .NET Framework
Author: Srinivas.KancherlaMember Level: Silver    
Rating: 1 out of 5Points: 15



Introduction



An exception is defined as an event that occurs during the execution of a program that disrupts the normal flow of instructions during the execution of a program. You could be selected in an interview if you give this answer to the interviewer, but if you give the same explanation to a friend who asked you to explain what an exception is, he may curse you as your definition is not that simple to him.

In simple terms an exception is defined as an unexpected behavior of the program such as - a full memory or when we try to access an array element which falls out side the size of the array or we try to divide a number by zero, etc.

During the procedural programming or in ASP or in COM, handling exceptions was cumbersome. The exception returned you nothing more than a code such as 0x800A01A8. To know the details of the exception you need to search the SDK for an explanation for the code. Sometimes, you may know the explanation, but couldn’t trace the exact line of code where the exception was actually raised.

To know where it was raised we use to follow divide and rule method of writing response.write() statements every 10 lines of code or so. Hence handling exceptions was nothing less than a nightmare. But not after .NET arrived.

Using .NET framework, handling exceptions was very easy than searching the SDK for the explanation of the exception number (in case of ASP/COM).

Exception is .NET can be handled at three levels.
1) At the procedure level
2) At the page level
3) At the application level

Let us see how to handle Exceptions at each of these levels.

1) Procedure Level:


To handle exceptions at this level we first need to identify the steps of code which possibly can generate an exception. After identifying those statements, keep the statements in between try and catch keywords. Use the finally keyword to do any memory cleaning work.

We can understand it better with an example.

We know that when we try to open a non-existing file programmatically, it will raise an exception. We try to use this point to understand exception handling at a procedure level.

Sub openFile()

Dim fileio As FileStream
Try
fileio = File.Open("C:\dotnetbooks.xml", FileMode.Open)
Response.Write("File is found")
Catch ex As Exception
Response.write(ex.Message)
Finally
fileio.Close()
End Try

End Sub


In the above code sample I was trying to open a file "dotnetbooks.xml" from drive C (and I know the file never exists in my C drive). So obviously line 5 will throw a FileNotFoundException.

Since I can guess that line 5 probably may throw an exception, I sandwiched it between try and catch statements. Let us see the flow of execution in this code snippet.

The flow will be continuous till line 5, at line 5 when the control tries to open the file, the file will not be found which leads to exception. Since the statement is between try and catch, instead of stopping the execution of program abruptly, the control will be passed to the catch statement in line 7, skipping the execution of line 6.

In the catch statement we simply write the details of the exception.

Finally is a statement which will be executed always; whether the exception is raised or not. So Finally is usually used to cleanup activities. In this case I used it to close the FileStream object.

Some important tips regarding Exceptions:
• A try statement can be followed by multiple catch statements.
• A catch clause can also be defined without having the Exception class parameter.
• A catch clause that doesn't name an exception class can handle any exception.
• When we are using more than one catch method then, your catch statements should move from more specific to least specific. i.e. If you have a catch for ArithmeticException class and Exception class then you must write the catch with ArithmeticException before you write the catch with Exception class.

2) Page Level:


Handling Exceptions at Page level is like, one handler will be written and any procedure/statement when raises exception will send the control to the handler.
Then handler written will handle the Event called Error of the control Page.

Let us see what it is all about using an example:

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Put user code to initialize the page here
Response.Write(Page.IsValid.ToString())
End Sub

Sub Page_Error(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Error

Response.Write(Server.GetLastError().ToString())
Context.ClearError()
End Sub


In the above example, I had written two handlers for the control Page, one is to handle the Load event and another to handle the Error event.

In the Page Load I am trying to call the IsValid property of control Page, which obviously will raise an Exception (know why?). However, the exception is not handled.
Still the execution will not terminate abruptly; instead, the control will go to Page_error method, as I had written a Page level Exception handler. In this Page_error method, I simply wrote the message on the page using Response.Write() method.

The conclusion is Page_Error handler will handle all the Exceptions raised on the Page.

3) Application Level:


At the Application Level, the event handler will handle the Exceptions raised by any Page of the application.

This event handler will be written in a special file called as Global.asax.vb. In a simple way, the method looks like this.
Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)

Response.Write(Server.GetLastError().ToString())
Context.ClearError()

End Sub


This method can handle any type of Exception raised in any Page of the application.



Responses


No responses found. Be the first to respond and make money from revenue sharing program.

Feedbacks      
Popular Tags   What are tags ?   Search Tags  
Sign In to add tags.
Three Levels of Exception Handling  .  Exception Handling in .NET  .  Exception Handling  .  

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: .NET Remoting - Part II
Previous Resource: Nullability Types in C# 2.0
Return to Discussion Resource Index
Post New Resource
Category: .NET Framework


Post resources and earn money!
 
More Resources



dotNet Slackers

About Us    Contact Us    Privacy Policy    Terms Of Use