This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 5 years ago.
My code updates & inserts into a bunch of tables. About 2 months ago I got the same error as the one below, I assumed it was because the exception it self is Nothing.
So I built in a test to check if it isn't nothing, write the exception details.
However, the error in the screenshot occurred again this morning. My question now is how does a code block like the one below result in the Exception being Null, and in which cases will an exception be Null?
Edited - This is different to this question because I want to know how an EXCEPTION can be Null/Nothing
Try
If t.DpaPosted = "N" Then
i += 1
OutputCount += 1
Dim SubAccountID As Integer = 0
If t.SubaccountId = 0 Then
SubAccountID = GetSubAccountID(t.DpaInId)
If SubAccountID = 0 Then
If DupAcc > 1 Then
UpdateLog(t.clientReference & " - Multiple CLOSED(Paid Up/Refunds outstanding) accounts.")
Else
SubAccountID = GetClosedSubAccountID(t.DpaInID)
If SubAccountID = 0 Then
UpdateLog(t.clientReference & " - No accounts found.")
End If
End If
End If
End If
If SubAccountID <> 0 Then
If t.DpaDocNo <> "0" Then
If q.Execquery("SELECT COUNT(1) FROM Transactions WHERE SubAccountID = " & t.SubaccountId & " AND TranTypeID = 6 AND TranAmount = " & t.DpaAmount & " AND DPANo = '" & t.DpaDocNo & "'") > 0 Then
HttpContext.Current.Response.Write("Sequence [" & t.DpaDocNo & "] already posted.<br/>")
dpaadapter.SetDpaPosted(t.DpaInId)
Else
PostDpa(SubAccountID, 6, t.DpaAmount, t.Dpadate, "0", t.DpaDocNo)
dpaadapter.SetDpaPosted(t.DpaInId)
End If
Else
PostDpa(SubAccountID, 6, t.DpaAmount, t.Dpadate, "0", t.DpaDocNo)
dpaadapter.SetDpaPosted(t.DpaInId)
End If
End If
If WriteOutput Then HttpContext.Current.Response.Write("Imported [" + i.ToString + "] of [" + dpa.Rows.Count.ToString + "]<br/>")
If OutputCount = 10 Then
OutputCount = 0
If WriteOutput Then
If HttpContext.Current.Response.IsClientConnected Then
HttpContext.Current.Response.Flush()
HttpContext.Current.Response.Write("<script>window.scrollTo(0,document.body.scrollHeight);</script>")
HttpContext.Current.Response.Flush()
End If
End If
End If
End If
Catch ex As Exception
Dim LogStr As String = ""
LogStr = "Record [" & i.ToString & "]. "
LogStr = "Ref [" & t.clientReference & "] - "
If ex.Message.ToString <> Nothing Then LogStr = LogStr & ex.Message.ToString Else LogStr = LogStr & "No Exception Message"
If ex.InnerException.ToString <> Nothing Then LogStr = LogStr & vbCrLf & ex.InnerException.ToString Else LogStr = LogStr & "No Inner Exception"
UpdateLog(LogStr)
SaveLog()
End Try
I can't actually see what code is triggering the exception, until I can fix the exception handling.
Some more information that might help
I am using asp.net V 4.0
The code is in a class, and the file is located in the appcode directory.
The issue doesn't always trigger
When running the code for a second/third time, the exception doesn't trigger again. So I can't recreate the error all the time.
Windows event viewer didn't log any exceptions for this page.
ANSWER
Found from this question.
An inner exception is the exception that caused the current exception.
It is used in cases when you want to surface a different exception
than the one that your code caught but you don't want to throw away
the original context.
In order for a new exception to have information about a previous one,
like you said, you pass it as constructor parameter to the new one.
Usually, a null inner exception means that the current exception is
root cause of the exceptional situation.
How about safeguarding your ex.InnerException? Once you make sure that an InnerException exists then you can access its methods and properties.
If ex.InnerException Is Not Nothing AndAlso ... Then
See this explanation (and read the accepted answer) about InnerException. It is not necessary to have an InnerException, unless the current exception was caused by another exception.
Related
I have the following code:
Public Function UltimoIngreso() As Date
Try
UltimoIngreso = Now.Date 'I am not ALWAYS getting the current date and time
' --other lines of code
Catch ex As Exception
' An error has occured so display an error message.
ReportBDLog.ReportErrorBD(ex, Me.GetType.ToString & "." & "UltimoIngreso" & vbCrLf & "Message: " & ex.Message & vbCrLf & "Source: " & ex.Source & vbCrLf, System.Reflection.MethodBase.GetCurrentMethod.ToString)
End Try
End Function
Sometimes, but not always, I get "Object reference not set to an instance of an object."
How do I ensure that Function UltimoIngreso always returns current date and time?
What am I missing?
This Function is used in an asp.net App.
I'm always getting error 3704. Operation is not allowed when object is closed.
Dim myConnection2, RSTitleList2
Set myConnection2 = CreateObject("ADODB.Connection")
Set RSTitleList2 = CreateObject("ADODB.Recordset")
myConnection2.Open "<%=connectionString%>"
sSQL1 = "Update FileInformation SET Status = 4 Where DataDefinitionID = 147 AND CustomerID = 71"
RSTitleList2.open sSQL1, myConnection2
if RSTitleList2.BOF and RSTitleList2.EOF then
msgbox("INSERT SUCCESSFUL")
frmProcess.cmdPublish.disabled = true
Else
msgbox("Not SUCCESSFUL")
msgbox(err.Number & " | " & err.description & " | " & err.Source)
End IF
msgbox(err.Number & " | " & err.description & " | " & err.Source)
It would help if you gave us the line where the line number which comes with the error message. However I can see one rather strange thing in your code
myConnection2.Open "<%=connectionString%>"
Why is "connectionstring" inside <%= %>. That syntax is used when you want display an asp variable within your html, eg
<h1>Welcome, <%= username %></h1>
When you're already in a block of asp code, just try
myConnection2.Open connectionString
I have an error handler in my global.asax as follows;
Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs when an unhandled error occurs
Dim ex = Server.GetLastError.GetBaseException
Dim lastErrorWrapper As HttpException = Server.GetLastError()
Dim lastError As Exception = lastErrorWrapper
If lastErrorWrapper.InnerException IsNot Nothing Then
lastError = lastErrorWrapper.InnerException
End If
My.ErrorHandler.LogError( _
"<BR/><BR/>URL: " & Request.RawUrl & _
"<BR/><BR/>STACK: " & ex.StackTrace & _
"<BR/><BR/>SOURCE: " & ex.Source & _
"<BR/><BR/>MESSAGE: " & ex.Message & _
"<BR/><BR/>TYPENAME: " & ex.GetType.ToString & _
"<BR/><BR/>INNER EXCEPTION: " & lastError.ToString & _
"<BR/><BR/>REFERRER: " & HttpContext.Current.Request.Url.AbsoluteUri & _
"<BR/><BR/>USER IP: " & Request.ServerVariables("REMOTE_ADDR") & " -- " & Request.ServerVariables("HTTP_USER_AGENT"))
End Sub
Obviously, this works great and sends me an email whenever there is an error. But, this is also true for any images that are not found in the file system. It gives me a "File does not exist." error. Is there a way to ignore logging errors for images that are not located on disk?
Cant you resolve the FileNotFoundException instead? If the exception should not occur then rather resolve the issue than suppressing it. To handle a known exception you can use the following code.
if(Server.GetLastError().GetBaseException() is System.Web.HttpException)
{
//You could check whether the
//Server.GetLastError().GetBaseException().Message contains the appropriate message
Debug.WriteLine("Suppressed FileNotFoundException");
}else
//Log an unhandled exception
var ex = Context.Error;
if (ex is HttpException)
{
var httpException = (HttpException)ex;
if (httpException.GetHttpCode() == (int)HttpStatusCode.NotFound)
return; // Do nothing 404
}
I know that this sounds very easy, or very simple, or you may search for the error code, but this is what I do - simple check if the error contains the message of dose not exist:
lastErrorWrapper.ToString().Contains("does not exist.")
Once in every few hundred times I get an error on the life site 'bout losing the object.
I've been checking and testing and testing but have not got a clue what's goin' wrong.
Anyone some bright idea?
The code is:
Dim MySqlCommand = New MySqlCommand(SQLC, MySqlConnect)
Try
Tries = 5
lg &= " Co("
Do
Try : MySqlCommand.Connection.Open()
Catch ex As Exception
lg &= " " & ex.Message
Wait(0.5)
End Try
If (MySqlCommand.Connection.State <> ConnectionState.Open) Then Tries -= 1
Loop While Tries > 0 And MySqlCommand.Connection.State <> ConnectionState.Open
lg &= ")"
Catch ex As Exception
lg &= ex.message
End Try
lg &= " " & LCase(Left(SQLC, 5)) & "(Mc"
Try
lg &= "En" : Dim ret = MySqlCommand.ExecuteNonQuery()
lg = ""
Catch ex As Exception
lg &= ":" & ex.message
End Try
if lg<>"" then Response.write(lg)
The Output is:
Co() updat(McEn:Object reference not set to an instance of an object.
Use a .net logging framework, like log4net. Log what is happening on your page.
In my experience, logging is the best way to catch intermittent bugs.
I have been trying to create an error handling path for our classic asp website. I have been searching for information for 3hrs now and have not found much even here on stack overflow. So if you can point me towards a duplicate great ... I couldn't find anything although it must exist.
My plan is the following ...
Have proper error handling in the stored procedures. Any errors that occur get inserted into an error table and are also raised back up to the application.
Have "On error resume next" set on the page. Then check the connection.errors collection for errors. As well as Server.GetLastError() property.
If there are any redirect to a page to to display safe error information and insert another record into another database table to tie the page name where the error occurred to the already existing database error in the database table mentioned above for later debugging purposes.
I have created the following page to to begin testing this out. However it is not working.
Dim cmd
Set cmd = Server.CreateObject("ADODB.Command")
cmd.ActiveConnection = con
cmd.CommandType = adCmdStoredProc
on error resume next
cmd.CommandText = "spReturnDBException"
cmd.CommandTimeout = 30 ' 2 minutes
cmd.Execute
dim objErr
set objErr = Server.GetLastError()
if objError.ASPCode <> 0 then
response.write("ASPCode=" & objErr.ASPCode)
response.write("")
response.write("ASPDescription=" & objErr.ASPDescription)
response.write("")
response.write("Category=" & objErr.Category)
response.write("")
response.write("Column=" & objErr.Column)
response.write("")
response.write("Description=" & objErr.Description)
response.write("")
response.write("File=" & objErr.File)
response.write("")
response.write("Line=" & objErr.Line)
response.write("")
response.write("Number=" & objErr.Number)
response.write("")
response.write("Source=" & objErr.Source)
else
response.write("There's nothing wrong.")
end if
Dim objErr2
for each objErr2 in objConn.Errors
response.write("<p>")
response.write("Description: ")
response.write(objErr2.Description & "<br />")
response.write("Help context: ")
response.write(objErr2.HelpContext & "<br />")
response.write("Help file: ")
response.write(objErr2.HelpFile & "<br />")
response.write("Native error: ")
response.write(objErr2.NativeError & "<br />")
response.write("Error number: ")
response.write(objErr2.Number & "<br />")
response.write("Error source: ")
response.write(objErr2.Source & "<br />")
response.write("SQL state: ")
response.write(objErr2.SQLState & "<br />")
response.write("</p>")
next
Free(cmd)
Free(con)
In the stored procedure I simply RAISERROR( N'Lets throw an error because I want to!', 17, 0 );
The output I get every time is as follows ...
ASPCode=ASPDescription=Category=Column=-1Description=File=Line=0Number=0Source=
Description: Help context: Help file: Native error: Error number: Error source: SQL state:
Why am I not getting any error information on the conn.Errors loop?
Resolved.
I was using a different connection object for the loop that loops through the connection.Errors ... copy paste error.
However on a side note ... I found it extremely difficult to find information on how to even do what I've so far.
here's some additional resources:
some general topics:
http://social.msdn.microsoft.com/search/en-US?query=Server.GetLastError%28%29&refinement=89
a specific example:
http://support.microsoft.com/kb/224070