SharePoint “handles” Access denied exceptions by catching the exception internally and then redirecting the user to a landing page where they can log in to the site. By default this is generally “_layouts/AccessDenied.aspx”.
Since SharePoint redirects the request to the default Access Denied landing page you cannot catch the UnAuthorizedAccessException as the redirect causes a ThreadAbortException to be thrown so your code will never get executed.
In order to handle a thrown
UnAuthorizedAccessException within your code you first need to set the property
CatchAccessDeniedException (part of the SPSecurity class) to false. Doing so means that the Access exceptions aren’t handled by the SharePoint platform and the request isn’t redirected.
bool orgcatchvalue = SPSecurity.CatchAccessDeniedException;
SPSecurity.CatchAccessDeniedException = false;
//your code that may throw an authorization exception
//Code to handle exception
//set the value back to what it was
SPSecurity.CatchAccessDeniedException = orgcatchval;