Handling Access denied exceptions in SharePoint

As developers, we like to handle all kinds of exceptions. Coming to SharePoint catching access denied exception is little tricky. I tried this with traditional try catch block and couldn't make it. Here is my snippet.

Problem

try
{
using(SPSite site=new SPSite(“URL”))
{
using(SPWeb web=site.OpenWeb()) /// Getting access denied here
{
}
}
}
catch(Exception ex)
{
// Log error and continue..
}
// Next set of statements.

With the above code snippet in place, exception is reaching to catch block and not continuing to next statement. 

Resolution 

The quick solution to handle this is, change security settings to not to catch access denied exception and continue. Thanks MS, we have ready to use API available and below is the final code with SPSecurity.CatchAccessDeniedException.

bool originalCatchValue = SPSecurity.CatchAccessDeniedException;
SPSecurity.CatchAccessDeniedException = false;
try{   using(SPSite site=new SPSite(“URL”))   {           using(SPWeb web=site.OpenWeb()) /// Getting access denied here           {}   }}catch (UnauthorizedAccessException ex){// Do something..}finally{   SPSecurity.CatchAccessDeniedException = originalCatchValue;}// continue execution.

References

http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spsecurity.catchaccessdeniedexception.aspx