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

No comments: