It’s a good practice to catch the UnauthorizedAccessException within your sharepoint code , it might be thrown if the logged in user does not have enought permissions to get some code execued in his security context .
However, the SharePoint platform handles this exception on the developer’s behalf by redirecting to _layouts/AccessDenied.aspx page .
To override this behavior, you can set the property SPSecurity.CatchAccessDeniedException to false, telling SharePoint “Please do not to handle the exception for me, I’ll take care of it“.
Example :
bool AccessDeniedflag = SPSecurity.CatchAccessDeniedException;
SPSecurity.CatchAccessDeniedException = false;
try
{
SPList list = web.GetList(web.ServerRelativeUrl+”/Lists/ListName”);
SPListItem item = list.Items[0];
item[“title”] = “ayman-elhattab.blogspot.com”;
item.Update();
}
catch(UnauthorizedAccessException ex)
{
// Redirect to your custom page
SPUtility.Redirect(“MyAccessDeniedPage.aspx”,SPRedirectFlags.RelativeToLayoutsPage,this.Context);
}
finally
{
SPSecurity.CatchAccessDeniedException = AccessDeniedflag;
}