How to catch a NullReferenceException?

5

When I test my application, it returns some specific data, but when the requested data is null, this unhandled exception error appears

ItriedtocapturehimbutIthinkI'mwrong.HowcanIleaveatreatmentthatwarnsinatextboxthattherequesteddatawasnotfound?

'BuscarinformaçõesviaGoogleBookAPI(precisaserarrumado)'PrivateSubButton3_Click(senderAsObject,eAsEventArgs)HandlesButton3.Click'Step1:-googleAPIurlresponsibleforreturningthebookdetailinJASONformat'ConstGOOGLEAPIURLAsString="https://www.googleapis.com/books/v1/volumes?q="

    If Me.txtISBN.Text <> String.Empty Then
        Dim requestURL As String

        'Step 2:- Reformed the URL to target particular ISBN number'
        requestURL = GOOGLEAPIURL + Me.txtISBN.Text.Trim() + "+isbn"

        'Step 3: created Http webrequest for URL'
        Dim wr As HttpWebRequest = HttpWebRequest.Create(requestURL)
        'Step4 : get the response of web request in http web response object'
        Dim resp As HttpWebResponse = wr.GetResponse()

        'Step 5: passes the response stream in stream reader'
        Dim sreader As New StreamReader(resp.GetResponseStream())
        'Step 6: parsing the reader(which is in Jason format) using JASON.NET'

        Dim rss = JObject.Parse(sreader.ReadToEnd())

        'Step 7: if object find the fetch the detail'

        If rss Is Nothing = False AndAlso rss.Count > 0 Then
            Me.lblBookName.Text = rss.Item("items")(0).Item("volumeInfo").Item("title").ToString()
            Me.lblSubtitle.Text = rss.Item("items")(0).Item("volumeInfo").Item("subtitle").ToString()
            Me.lblAuthor.Text = rss.Item("items")(0).Item("volumeInfo").Item("authors").ToString().Replace("[", "").Replace("]", "").ToString()
            Me.lblPublisher.Text = rss.Item("items")(0).Item("volumeInfo").Item("publisher").ToString()
            Me.lblPublishedDate.Text = rss.Item("items")(0).Item("volumeInfo").Item("publishedDate").ToString()
            Me.lblPageCount.Text = rss.Item("items")(0).Item("volumeInfo").Item("pageCount").ToString()

            'Captura de erro'
            Try
                rss = True
            Catch ex As Exception

            End Try
        Else
            MsgBox("Nada aqui")
        End If
    Else

        Me.lblMessage.Text = "Please enter the ISBN number"
    End If
    
asked by anonymous 26.11.2015 / 01:24

3 answers

3

First, reinforcing what @bigown said

  

Please, never use try-catch if you are not sure what you are doing. It is not solution, it is problem increase.

From what I understand and got to see from the code, you are trying to get the data from a JSON and play at TextBoxes . What is happening is that you are trying to access some element that does not exist in JSON. Since you can not change the response you're getting from the API, you'll need to validate if the data / elements actually exist in JSON before attempting to access them.

/ p>
if(rss.Item("items")[0] != null && rss.Item("items")[0].Item("volumeInfo") != null)
{
    if(rss.Item("items")[0].Item("volumeInfo").Item("subtitle") != null)
        lblBookName.Text = rss.Item("items")[0].Item("volumeInfo").Item("subtitle").ToString();
    else
        lblBookName.Text = "Dado não encontrado";
}

This may not be the best way to validate this. Particularly I'd save% w / o% on a variable and use it to check if the items inside it are null or not. But this is a matter of taste and the important thing is that you can understand that the solution is not to use rss.Item("items")[0].Item("volumeInfo") , you just need to check if the elements exist before trying to access them.     

26.11.2015 / 11:53
8

This is a programming error, so you should not catch any exceptions. To do this would be to try to throw the dirt under the rug. This error is not normal. This is the symptom that there is something wrong with the code and the solution is to fix the error.

As there are no details, I can not say what the exact solution is, but in general terms what should be done is to prevent this exception from being thrown. That is, you should check if the variable that is null is null before you try to access it. Can not access a null value. Simple as that.

Any other solution you try will be gambiarra will produce a bad code.

And please, never use try-catch if you are not sure what you are doing. It is not solution, it is problem increase.

    
26.11.2015 / 03:29
0

After looking at the section that @jbueno passed me, I adapted to use it in VS and got the expected result!

   If Me.lblPublisher.Text = rss.Item("items")(0).Item("volumeInfo").Item("publisher") = True Then
                Me.lblPublisher.Text = rss.Item("items")(0).Item("volumeInfo").Item("publisher").ToString()
            Else
                lblPublisher.Text = "dado não encontrado"
            End If

With this I stopped using Try Catch (since my intention was to ignore NullReferenceException) and I was able to continue running the program without leaving any problem in the code and still informing the user about which data could not be found! p>

Thanks: D

    
27.11.2015 / 17:50