error.aspx
<%@ Page Language="VB" %>
<script language="VB" runat="server">
Sub CauseHandledError(Sender As Object, E As EventArgs)
' Start looking for errors:
Try
' Cause errors:
' These lines will cause a NullReferenceException:
Dim foo As String = Nothing
Response.Write(foo.ToString())
' These lines will cause an HttpException:
'Dim cnnTest
'cnnTest = Server.CreateObject("ADODB.ThisObjectDoesntExist")
' Notice the multiple catches. An exception will only be caught
' by a catch if it matches the type of exception the catch specifies.
' The 3rd catch catches generic exceptions and should catch most any
' error. This allows you to set up different error handling
' depending on the type of error. You can also add When clauses
' to the end of a catch like I did on the 3rd one to further branch
' your error handling if you need to.
Catch ex As NullReferenceException
Response.Write("<p>This script just handled a NullReferenceException error.</p>")
Response.Write("<pre>" & ex.ToString() & "</pre>")
Catch ex As HttpException
Response.Write("<p>This script just handled an HttpException error.</p>")
Response.Write("<pre>" & ex.ToString() & "</pre>")
Catch ex As Exception When 1=1
Response.Write("<p>This script just handled an error.</p>")
Response.Write("<pre>" & ex.ToString() & "</pre>")
Finally
Response.Write("<p>This is in the optional finally block which is always executed if an error occurs.</p>")
Server.ClearError()
End Try
End Sub
Sub CauseUnhandledError(Sender As Object, E As EventArgs)
Dim cnnTest
cnnTest = Server.CreateObject("ADODB.ThisObjectDoesntExist")
End Sub
' You can handle any errors that occur outside of your structured
' error handling here. This Sub is automatically called in the
' event of an unhandled run-time error.
Sub Page_Error(sender As Object, e As EventArgs)
Dim strErrorMessage As String
strErrorMessage = Request.Url.ToString() & vbCrLf _
& "<pre>" & Server.GetLastError().ToString() & "</pre>"
Response.Write(strErrorMessage)
Server.ClearError()
Response.Write("<p>Click <a href=""error.aspx"">here</a> to go back to the sample with no errors.</p>")
End Sub
</script>
<html>
<head>
<title>ASP.NET Error Handling Sample</title>
</head>
<body>
<hr />
<form runat="server">
<asp:button text="Cause Handled Error" OnClick="CauseHandledError" runat="server" />
<asp:button text="Cause Unhandled Error" OnClick="CauseUnhandledError" runat="server" />
</form>
<hr />
<p>
Click <a href="http://www.asp101.com/samples/error_aspx.asp">here</a> to read about and download the source code.
</p>
</body>
</html>