In a global.asax file put the application_error event

protected void Application_Error(object sender, EventArgs e)
        {
            Server.Transfer("ErrorPage.aspx");//this will show customized error page
        }

In the ErrorPage.aspx.cs file you need to write this code

Exception ex = HttpContext.Current.Server.GetLastError().GetBaseException();

            errMessage = ex.Message.ToString();
            errInnerException = ex.ToString();
            errStackTrace = ex.StackTrace.ToString();

            Server.ClearError();
            Response.Write(ErrMessage); //displays the last error