Handling 404 Error (Not Found) in ASP.NET

Consider that you configured a custom 404 page in the web.config file in the customErrors section. So whenever a user requests a non-existent aspx page, ASP.NET run-time returns a well-formatted message to the user.

Also, you have a page that shows articles from a database according to the article ID passed in the url (for example page.aspx?id=34). But if the user passes an article ID that doesn't exist the page must return code 404 (Not Found) and show the custom 404 page like in the previous situation.

Fortunately, you don't need to parse the customErrors section to get the name of the custom 404 page. Just throw HttpException.

throw new HttpException(404, "Page you requested is not found");

ASP.NET run-time will catch the exception and will redirect to the custom 404.