Thursday, November 1, 2007

Asp.Net Exception Handling Best Practices

@@Use the TRY-CATCH block at outermost level / Event. For Eg. If event is Btn_Click which internal calls function “Add EMP” which internally calls “Add EMPDetail” in this case you should apply the TRY-CATCH block at Btn_Click & for others use only
TRY-FINALLY.

@@ Use EXCEPTION.TOSTRING instead of Ex. message which will give you only the message. But the ex.Tostring () will give you the complete stack track.


@@ avoid using Throw ex it will erase the stack information use only THROW.
If still you want to use Throw ex then write like this
Throw ex new ApplicationException (“Customized mesg”, Ex)


@@A lot of scenarios needs that exceptions are serializeable. When deriving from another exception class, don't forget to add that Serializeable attribute. You'll never know when your method will be called from Remoting components or Web Services.

@@Do not always write exception handling for your code.Sometime its better to handle the errors using if – else condition and returning true/false for desired conditions for Eg.
void EmpExits ( string EmpId){//... search for employeeif ( dr.Read(EmpId) ==0 ) // no record found, ask to create{throw( new Exception("Emp Not found"));}} The best practice is :bool EmpExits ( string EmpId){//... search for Productif ( dr.Read(EmpId) ==0 ) // no record found, ask to create{return false}}
@@Avoid exception handling inside loops, if its really necessary implement try/catch block surround the loop

@@Best way to handle exception is to create a hierarchy like.

Catch Ex as SqlException ‘It will catch only sql exceptions
Catch Ex as ApplicationException ‘It will catch only application exceptions
Catch Ex as Exception ‘This is parent class of exception so rest of all exceptions it will catch
Do not write “Catch ex as Exception” at the Top, otherwise it will catch all exceptions and below catch will become dead code.

For more information
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnbda/html/exceptdotnet.asphttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconbestpracticesforhandlingexceptions.asp

View State Is Invalid" Error Message When You Use Server.Transfer

Server.Transfer transfers execution from the source page to the destination page on the server. As far as the browser client is concerned, it made one request and the initial page is the one responding with content (this point is confusing new ASP.NET developers as the browser still shows the URL of previous page.)
The advantage of this approach is one less round trip to the server from the client browser.** keep in mind that Response.Redirect requires 2 round trips to Server** Also, Another advantage is querystring and form control values are available on destination page. For eg. If source page contains a Textbox (Userid - Name of control) and developer would like to have this value on destination page then use Request.Form("Userid") **Remember the old days of Asp**
Now in this way values can be reterieved. If user doesn't want these values to be perserved then simply send the second parameter of Server.Tranfer as False ("PreserveForm"). Till this point everything goes well with Server.Transfer. But....

As soon as user writes Server.Transfer("Destination.aspx",True) you wil get an error
"View State Is Invalid". This is known bug of microsoft. If you want to know more click here

http://support.microsoft.com/default.aspx?id=kb;en-us;Q316920


One thing to keep in mind if the first page wrote something to the Response buffer and you don’t clear it, then any output from the second page will be added to the output of the first. This is often the cause of a **weird** behavior where it seems that a page is returning two different pages. Also, since the transfer happens on the server, you cannot transfer a request to an external site.

Server.Transfer / Response.Redirect Bug

One fine day I got an error in code "Thread abort exception", where as I was not using any threading code but simply using Response.Redirect. After doing lot of study/Research found solution that, Response.Redirect works on browser only.. That it sends request to browser to change the page. ** 2 round trips are required**.
Here the above error comes because the thread in which your pageone.aspx is executing breaks when Response.Redirect is encountered.

Optimized Solution : - See the second parameter with Response.Redirect ("something.aspx",EndResponse), Here if you write ("something.aspx",False) you are going to land in trouble. So better to use ("something.aspx",True) i.e redirect to given page and end the current thread.

Raw Solution :- Generally developers think that writting try-catch block for every error is good practice. But this is not the real world solution, you should try to avoid the unnecessary try-catch block coz using try-catch excessively is also a performance penalty..

If you go the "Thread Abort Exception" don't use the below code

Try
Response.Redirect("destination.aspx")
Catch ex as threadabortexception
'leave it blank
end try
A good solution to this issue is use response.redirect("page name",false).The second parameter is "Endresponse" so set value to false.


The next is Sever.Transfer.... Some time this also fires the above "Thread Abort Exception" so either change Server.Transfer with Response.Redirect or set the second parameter of Server.Transfer to False (Server.Transfer("destination.aspx",false))