Sunday, October 14, 2012

Object reference not set to an instance of an object

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

Complete the catch function


It is time to supplement the use of the catch function to make the error message more attractive. Here is the code:
''' <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


        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.StackTrace, MsgBoxStyle.Exclamation, ex.Message) 'add basic error message here
        End Try

       
    End Sub
End Class



Adding arguments to the function Msgbox, we enrich the MsgBox window. Here's what happens when you run the function and the program crashes:

Now all the functions that you create will have the function Try and catch function. Throughout your catch function, I recommend you use the StackTrace property with the small exclamation icon. Yes, a picture is worth a thousand words, do not forget.

This technique protection code is very simple and only take 4 lines! Use it.

About

I invite you to visit my blog for more articles and leave a comment.
Check Technologies represents more than 10 years .... Computer and computer aided design.







No comments:

Post a Comment