You need to to add the customErrors section in the web.config file and turn on custom errors. Add an error element for HTTP status code 404 (resource not found). The following markup shows an example.
.
By doing this you will not need to write code to tell the browser that it is a "404 Error", and you can still write your own code in your custom error page, that is you can retrieve the url and etc..