Object reference not set to an instance of an object
One of the biggest mistakes in programming is not allocate space for an object. We often think of declaring variables, but should always ensure that these variables are created. Or, declare a variable does not create the object. She does an object is of type String, Integer, Double, etc.
The following code illustrates the problem well:
''' <summary>
''' crash test and how to improve your coding
''' </summary>
''' <remarks></remarks>
Public Class Form1
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
End Sub
''' <summary>
''' pressing button1 will crash he program
''' this crash is the typical crashing type for all beginners
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
''' <remarks></remarks>
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim aString() As String 'declare and array only
'a crash will occur and the code won't be able to handle it
MsgBox(aString(0)) ' you do something with the array and and array is nothing
End Sub
End Class
|
When the code reaches the Msgbox, obviously Msgbox function tries to read the first box of the table, however, is zero. I would add that this table cell is not only zero, it does not exist and does not refer to anything.
Obviously, the example is an array, but the problem would be put on any object. Several solutions exist to control our computer codes. Some work better than others depending on the situation.
But here is a programming method that everyone should do at the beginning, use the try.
Try
'a crash will occur and the code won't be able to handle it
MsgBox(aString(0)) ' you do something with the array and and array is nothing
Catch ex As Exception
End Try
|
Try the function says it very well in English, is to try. Try a code because n, is never sure of the result. Early use functions will try to save you time and money.
The program I love to use:
Sample Code :
Hiç yorum yok:
Yorum Gönder