21 Ocak 2015 Çarşamba

Object reference not set to an instance of an object 2

 Object reference not set to an instance of an object (part 2)


In a previous article, I demonstrated a simple and common error in programming: not create an object (or element).
When running the computer code, an error "fatal" occurs and the program stops. To solve the problem, I have not corrected, but I have rather isolated.
Here is an overview of the code from the previous article:

''' <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.EventArgsHandles 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.EventArgsHandles Button1.Click
        Dim aString() As String 'declare and array only


        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

       
    End Sub
End Class



The function Try without a following error might occur:


Thus, the function Try isolates and captures the error preventing some way to stop whole the program. Keep in mind that Try do not correct the problem really. Indeed, the error in this case is an array is declared without assigning memory space for strings. A rookie mistake but also for the more experienced simply by accident.
But it was possible that the function Try detects an error may prevent the user. That is to say, prevent the user program so that it can then inform the designer of the computer code of the situation. Would this be the beginning of a quality control?
The answer to the question is yes. Yes, it is possible to capture the error. Yes the catch function which in French means  attraper .
I don’t want to make a big this article too long. I invite you to do this: add a Msgbox after the catch line.



        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
            MsgBox(ex.Message) 'add basic error message here
        End Try

       


When you execute the code, instead of crashing the entire program, at least it will display a "controlled" message and finish the function.








Hiç yorum yok:

Yorum Gönder


Günün Fırsatı
isim isim isim isim isim isim