How to capture a Nullreferenceexception?

Asked

Viewed 178 times

6

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

inserir a descrição da imagem aqui

I tried to capture him but I think I’m making a mistake.
How can I leave a treatment that warns in a textbox that the requested data was not found?

'Buscar informações via GoogleBook API (precisa ser arrumado)'
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
    'Step 1:- google API url responsible for returning the book detail in JASON format'
    Const GOOGLEAPIURL As String = "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

3 answers

8

This is a programming error so you should not capture any exception. To do this would be to try to throw the dirt under the mat. This error is not normal, it is the symptom that there is something wrong in the code and the solution is to fix the error.

As there are no details I can not say which is the exact solution but in general lines what should be done is to avoid that this exception be launched. That is, you should check that the variable that is null is null before trying to access it. You cannot access a null value, simple like this.

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

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

  • So my intention was to capture the exception and continue running the Try block to get the remaining data, I know this is not good practice, but I would have plausible reasons to explain the pq....

  • If you had, you would have explained. This makes no sense under any circumstances that I know. The try-catch that you used is probably the strangest thing I’ve ever seen.

  • would you have explained it here in the question or commented on the code? Anyway... it’s the method I found to not stop the execution of the program, I put only one Msgbox warning about data that was not found. So I came to ask about what other method you could be using... :/

  • I don’t think you read my answer. The program is stopping for a programming error. You have to fix it and not let it stop. You want to throw the dirt under the carpet, this does not solve anything. The method is to check (`if``) if the information is present. If it is not, you inform the user of this situation, but do not let the program generate an exception. If you want to learn about exceptions, I wrote a lot about this: http://answall.com/search?q=user%3A101+%5Bexception%5D

  • I got it, I got it wrong, but thanks anyway. I was able to solve it with the adapted excerpt @jbueno gave me, and I understood now what you meant about playing under the rsrs . Vlw itself ;)

3


First, reinforcing what @Maniero said

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

From what I understand and can see from the code, you are trying to take the dice of a JSON and play in TextBoxes. What is happening is that you are trying to access some element that does not exist in JSON. Since you cannot change the response you are receiving from the API, you will need to validate whether the data/elements actually exist in JSON before trying to access them.

I do not know very well how it works in VB.NET and how your question has to tag C#, first I will answer in C# and then edit the answer to put the code in VB.NET.

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 it. Particularly would I save rss.Item("items")[0].Item("volumeInfo") in a variable and would use it to check whether the items within it are null or not. But that’s a matter of taste and the important thing is that you can understand that the solution is not to use try-catch, you just need to check if the elements exist before trying to access them.

  • Poxa valeu @jbueno, I did it! With this snippet of your code, I adapted it for VS and it worked!! ;código 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 = "data not found" End If código not edit to put the code here

0

After looking at the section @jbueno gave 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 managed to continue running the program without leaving any problem in the code and still informing the user about which data can not be located!

Thank you :D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.