SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

When this code executes in a custom web part:

   ...Offending code here...
catch (System.UnauthorizedAccessException e)
     //Do nothing if the user doesn't have access to the site or list.

I am redirected to the _layouts/AccessDenied.aspx error page that displays: "Error: Access Denied". Shouldn't the handled exception be ignored? Am I missing something?

share|improve this question
up vote 1 down vote accepted

If the user doesn't have access to the page your web part is running on then it will never reach that code.

You might be able to override PreInit or one of the other page lifecycle events, but even then I don't see how your specific code is going to override the fact that they don't have access.

Here's a page lifecycle reference:

You can also try something like this, but again you have to be able to set it as early on in the page lifecycle for it to have any chance of working:

share|improve this answer
The web part is actually on a site that the user does have access to. However, the code aggregates list content from multiple subsites, some of which the user does not have access to. When iterating through the SPWeb objects, the error is raised when the list is queried. I just want to wrap that it a try/catch block but it seems to redirect me regardless. – Ben Aug 12 '11 at 18:34
OK, in that case use the approach in the 2nd link I posted...setting SPSecurity.CatchAccessDeniedException before executing your code and returning it to original value after you're done. – Rob D'Oria Aug 12 '11 at 18:37
I found a workaround - we keep track of which sites users should have access to in a database. I'm now only iterating through sites the user should have access to and avoiding the error. Thanks for the help. – Ben Aug 12 '11 at 19:27

This is because SharePoint's error handling treats the UnauthorizedAccessException as a special exception and will ALWAYS redirect to the access denied page, there's even a special method to handle it:


You can turn this of by settings the following property:

SPSite.CatchAccessDeniedException = false;

P.S. it is not necessary to use an external database to get a list of all SPSite's a user has access to, this can be done using Search:Sites i have access to by Wonderlaura.

She mentions it is enterprise only, but since you are doing this in code, it'll work for any version but Foundation / WSS3 by using the FullTextSqlQuery class and then query for contentclass:STS_Site contentclass:STS_Web contentClass:sts_listitem_850

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.