Results 1 to 25 of 25

Thread: [RESOLVED] How to use Try... Catch in following code?

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Feb 2023
    Posts
    128

    Resolved [RESOLVED] How to use Try... Catch in following code?

    If no internet connection exist stop, (not execute any other codes), with a message like "No Internet connection , Try again later...".

    Code:
     Private Sub btnGetGold_Click(sender As Object, e As EventArgs) Handles btnGetGold.Click
         Dim pos1 As Long, pos2 As Long, gold As String
         Dim request As WebRequest = WebRequest.Create("https://www.livepriceofgold.com/greece-gold-price.html")
         Dim response As HttpWebResponse = CType(request.GetResponse(), HttpWebResponse)
             Dim datastream As Stream = response.GetResponseStream
             Dim reader As New StreamReader(datastream)
             Dim strData As String = reader.ReadToEnd
             pos1 = InStr(strData, "22GXAUUSD_EUR_BID") + 18
             pos2 = pos1 + 5
             gold = strData.Substring(pos1, pos2 - pos1)
             TextBox5.Text = Val(gold)
         Using conn As New SQLiteConnection(connection)
             conn.Open()
             Dim query As String = "SELECT SUM(Gold_gr) from users"
             Using command As New SQLiteCommand(query, conn)
                 TextBox6.Text = Convert.ToDecimal(command.ExecuteScalar())
             End Using
             TextBox5.Select()
    
         End Using
    
     End Sub
    Many ways exist to Babylon.
    Only the shortest is the Best.

  2. #2
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    8,758

    Re: How to use Try... Catch in following code?

    Wrap the line with request.GetResponse in the Try....Catch. That is where your code will try to use the internet so that is where the point of failure would be if there is a problem with your internet connection.
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena

    Copy/move files using Windows Shell | I'm not wanted

    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. - jmcilhinney

    The threads I start are Niya and Olaf free zones. No arguing about the benefits of VB6 over .NET here please. Happiness must reign. - yereverluvinuncleber

  3. #3
    King of sapila
    Join Date
    Oct 2006
    Location
    Greece
    Posts
    6,703

    Re: How to use Try... Catch in following code?

    greece-gold-price ???
    ἄνδρα μοι ἔννεπε, μοῦσα, πολύτροπον, ὃς μάλα πολλὰ
    πλάγχθη, ἐπεὶ Τροίης ἱερὸν πτολίεθρον ἔπερσεν·

  4. #4
    PowerPoster wqweto's Avatar
    Join Date
    May 2011
    Location
    Sofia, Bulgaria
    Posts
    5,583

    Re: How to use Try... Catch in following code?

    Quote Originally Posted by sapator View Post
    greece-gold-price ???
    Relax, it's only goverment selling sovereign gold for peanuts. . . Just what EU told them to do :-))

    cheers,
    </wqw>

  5. #5
    King of sapila
    Join Date
    Oct 2006
    Location
    Greece
    Posts
    6,703

    Re: How to use Try... Catch in following code?

    WHAT?! HOW DARE YOU?!
    That is....
    Accurate.
    ἄνδρα μοι ἔννεπε, μοῦσα, πολύτροπον, ὃς μάλα πολλὰ
    πλάγχθη, ἐπεὶ Τροίης ἱερὸν πτολίεθρον ἔπερσεν·

  6. #6
    Member
    Join Date
    Sep 2024
    Posts
    49

    Re: How to use Try... Catch in following code?

    Code:
    If My.Computer.Network.IsAvailable = False Then
        MsgBox("No network connection detected. Cancelling all operations.", MsgBoxStyle.Critical, "Network Error")
        End
    End If

  7. #7
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    39,518

    Re: How to use Try... Catch in following code?

    It would be best to also wrap the SQL connection steps in an exception handler, and not the same one that you have for the request. Getting an exception from a SQL call is pretty rare, normally, as your database is usually going to be highly reliable, but it IS a place where an exception that can only be dealt with through exception handling can arise.
    My usual boring signature: Nothing

  8. #8
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    8,758

    Re: How to use Try... Catch in following code?

    Quote Originally Posted by Red.x View Post
    Code:
    If My.Computer.Network.IsAvailable = False Then
        MsgBox("No network connection detected. Cancelling all operations.", MsgBoxStyle.Critical, "Network Error")
        End
    End If
    I dislike this approach because the chances of the internet failing right after that check succeeds is non-zero. I think it's a bad practice to write code in a way that relies on a low probability of exceptional circumstances.
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena

    Copy/move files using Windows Shell | I'm not wanted

    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. - jmcilhinney

    The threads I start are Niya and Olaf free zones. No arguing about the benefits of VB6 over .NET here please. Happiness must reign. - yereverluvinuncleber

  9. #9
    Member
    Join Date
    Sep 2024
    Posts
    49

    Re: How to use Try... Catch in following code?

    Quote Originally Posted by Niya View Post
    I dislike this approach because the chances of the internet failing right after that check succeeds is non-zero. I think it's a bad practice to write code in a way that relies on a low probability of exceptional circumstances.
    Help him out
    Don't talk like a grandma

  10. #10
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    8,758

    Re: How to use Try... Catch in following code?

    Quote Originally Posted by Red.x View Post
    Help him out
    Don't talk like a grandma
    I already did. This is the answer:-
    Quote Originally Posted by Niya View Post
    Wrap the line with request.GetResponse in the Try....Catch. That is where your code will try to use the internet so that is where the point of failure would be if there is a problem with your internet connection.
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena

    Copy/move files using Windows Shell | I'm not wanted

    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. - jmcilhinney

    The threads I start are Niya and Olaf free zones. No arguing about the benefits of VB6 over .NET here please. Happiness must reign. - yereverluvinuncleber

  11. #11
    PowerPoster ChrisE's Avatar
    Join Date
    Jun 2017
    Location
    Frankfurt
    Posts
    3,091

    Re: How to use Try... Catch in following code?

    Quote Originally Posted by Red.x View Post
    Help him out
    Don't talk like a grandma
    send a Ping to check

    ... just one Ping
    https://www.youtube.com/watch?v=jr0JaXfKj68
    to hunt a species to extinction is not logical !
    since 2010 the number of Tigers are rising again in 2016 - 3900 were counted. with Baby Callas it's 3901, my wife and I had 2-3 months the privilege of raising a Baby Tiger.

  12. #12
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    39,518

    Re: How to use Try... Catch in following code?

    One ping isn't enough to figure everything out. One ping is good enough for some things, but it's not the case that one ping will rule them all.
    My usual boring signature: Nothing

  13. #13
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    39,518

    Re: How to use Try... Catch in following code?

    I agree with Niya, of course. Exception handling should be used for exceptional circumstances. You can never be utterly sure that a network connection will be available, and will remain available. Checking that there is a network connection available is a good thing to do, as it avoids some nuisance failures, but it doesn't catch all possible failures in a network operation, so any network operation should be wrapped in exception handling, and so should any SQL operation. In both cases, the key is that your program is reaching outside itself to some other process, and you program can't control what that other process does or how it behaves, so you have to protect yourself, which is what exception handling does.
    My usual boring signature: Nothing

  14. #14

    Thread Starter
    Addicted Member
    Join Date
    Feb 2023
    Posts
    128

    Re: How to use Try... Catch in following code?

    thanks to all.
    I have wraped the whole code in the Button.click event.
    if the internet connection is not avalaible any operations, variables,textboxes and SQL operations are pointless.
    this include if something wrong is with the SQL Operation, but i will have the same message?

    Code:
     Private Sub btnGetGold_Click(sender As Object, e As EventArgs) Handles btnGetGold.Click
         Try
             Dim pos1 As Long, pos2 As Long, gold As String
             Dim request As WebRequest = WebRequest.Create("https://www.livepriceofgold.com/greece-gold-price.html")
             Dim response As HttpWebResponse = CType(request.GetResponse(), HttpWebResponse)
             Dim datastream As Stream = response.GetResponseStream
             Dim reader As New StreamReader(datastream)
             Dim strData As String = reader.ReadToEnd
             pos1 = InStr(strData, "22GXAUUSD_EUR_BID") + 18
             pos2 = pos1 + 5
             gold = strData.Substring(pos1, pos2 - pos1)
             TextBox5.Text = Val(gold)
             Using conn As New SQLiteConnection(connection)
                 conn.Open()
                 Dim query As String = "SELECT SUM(Gold_gr) from users"
                 Using command As New SQLiteCommand(query, conn)
                     TextBox6.Text = Convert.ToDecimal(command.ExecuteScalar())
                 End Using
                 TextBox5.Select()
             End Using
         Catch ex As Exception
             MsgBox("No Internet connection.. Try again later...")
         End Try
     End Sub
    Last edited by marsias; Nov 29th, 2024 at 11:42 PM.
    Many ways exist to Babylon.
    Only the shortest is the Best.

  15. #15
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,840

    Re: How to use Try... Catch in following code?

    That's a VERY bad solution. If there is a problem with the database, you're going to lie to the user and tell them that there's no internet connection. What if that happens and the user checks their internet connection, finds it's fine and then tries again, only to get the same message?

    Why ask a question of you're just going to ignore the good advice that people take the time and make effort to provide to you? You should almost NEVER catch just an Exception. You should pretty much always know exactly what types of exceptions can be thrown by your code and catch those specifically, leaving any unexpected exceptions to be handled by a global exception handler.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  16. #16

    Thread Starter
    Addicted Member
    Join Date
    Feb 2023
    Posts
    128

    Re: How to use Try... Catch in following code?

    This is not the final solution.....
    The app should work even if i dont have a internet connection!
    i try to figure out where to put the database exception.
    Many ways exist to Babylon.
    Only the shortest is the Best.

  17. #17
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,840

    Re: How to use Try... Catch in following code?

    Quote Originally Posted by marsias View Post
    i try to figure out where to put the database exception.
    Around the database code. Pull all the UI stuff out and do it at the end, assigning the data to variables first. Wrap the WebRequest code in one Try block and put a Return in the Catch for that, then put the ADO.NET code in another Try block and put a return in that Catch block too. If no exceptions are caught, you'll end up at the code that populates and manipulates the UI.
    Code:
    Try
        'Web stuff here
    Catch
        '...
        Return
    End Try
    
    Try
        'Database stuff here
    Catch
        '...
        Return
    End Try
    
    'UI stuff here
    That's basically what people have already said.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  18. #18

    Thread Starter
    Addicted Member
    Join Date
    Feb 2023
    Posts
    128

    Re: How to use Try... Catch in following code?

    the database exception goes to the form load event.
    It works but starts the form with empty fields,
    How to make that the app does not load the form and close ?

    ok found with add me.close() before return

    Code:
    Public Sub ShowData()
        table.Rows.Clear()
        Try
            Dim command As New SQLiteCommand("SELECT id,Ruler,Gold_Coin,year,Gold_gr,Image FROM users order by year", connection)
            Dim adapter As New SQLiteDataAdapter(command)
            adapter.Fill(table)
        Catch ex As Exception
            MsgBox("No Database Connection..Contact your admin..")
    me.close()
            Return
        End Try
        TextBox1.Text = table.Rows(index)(1).ToString
        TextBox2.Text = table.Rows(index)(2).ToString
        TextBox3.Text = table.Rows(index)(3).ToString
        TextBox4.Text = table.Rows(index)(4).ToString
        Dim imgData As Byte() = CType(table.Rows(index)(5), Byte())
        Using ms As New MemoryStream(imgData)
            PictureBox1.Image = Image.FromStream(ms)
        End Using
        DataGridView1.DataSource = table
    End Sub
    Last edited by marsias; Nov 30th, 2024 at 03:02 AM.
    Many ways exist to Babylon.
    Only the shortest is the Best.

  19. #19
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,840

    Re: How to use Try... Catch in following code?

    You're still catching the base Exception instead of the specific type(s) of exception you expect to be thrown.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  20. #20
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    39,518

    Re: How to use Try... Catch in following code?

    I'm not so opposed to the base exception for SQL code, especially just starting on a program. For most things I've done, errors in DB code are first because of typos in the SQL. Those are just going to get caught during debugging, and I don't care what exception is thrown for that purpose. Once those trivial issues are cleaned up, any exception in the DB code is usually so utterly fatal that I'm not even going to TRY (or catch) to recover, I'm just going to exit as politely as I can. If it becomes apparent that there is one type of exception that has some meaningful way to recover, then that can be split out. I rarely find that to be the case with SQL.
    My usual boring signature: Nothing

  21. #21
    PowerPoster
    Join Date
    Sep 2005
    Location
    Modesto, Ca.
    Posts
    5,288

    Re: How to use Try... Catch in following code?

    I don't like doing this,

    Code:
        Catch ex As Exception
            MsgBox("No Database Connection..Contact your admin..")
    me.close()
            Return
        End Try
    You get more information with,

    Code:
            Catch ex As Exception
                MessageBox.Show(ex.Message)
            End Try
    or

    Code:
            Catch ex As Exception
                MessageBox.Show(ex.ToString)
            End Try
    The "ex" message isn't always helpful but many times it can be.

  22. #22
    PowerPoster PlausiblyDamp's Avatar
    Join Date
    Dec 2016
    Location
    Pontypool, Wales
    Posts
    2,762

    Re: How to use Try... Catch in following code?

    I would typically avoid showing those kind of error messages to an end user, they are often overly technical and can even reveal information that could be used to identify security weakness.

    Ideally those errors should be logged somewhere, and a more user friendly message displayed to the users.

  23. #23
    PowerPoster
    Join Date
    Sep 2005
    Location
    Modesto, Ca.
    Posts
    5,288

    Re: How to use Try... Catch in following code?

    Quote Originally Posted by PlausiblyDamp View Post
    I would typically avoid showing those kind of error messages to an end user, they are often overly technical and can even reveal information that could be used to identify security weakness.

    Ideally those errors should be logged somewhere, and a more user friendly message displayed to the users.
    I don't mind logging the error, just as long as it's available in some form to aid in debugging.

    I would just display it while I am developing the program then change it to logging at the end.
    Last edited by wes4dbt; Nov 30th, 2024 at 05:28 PM.

  24. #24
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,840

    Re: How to use Try... Catch in following code?

    Quote Originally Posted by wes4dbt View Post
    I don't mind logging the error, just as long as it's available in some form to aid in debugging.

    I would just display it while I am developing the program then change it to logging at the end.
    That's why you use Debug.WriteLine. You'll see that in the Output window while debugging but it won't affect a Release build at all without the need to modify the code.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  25. #25
    PowerPoster
    Join Date
    Sep 2005
    Location
    Modesto, Ca.
    Posts
    5,288

    Re: How to use Try... Catch in following code?

    Quote Originally Posted by jmcilhinney View Post
    That's why you use Debug.WriteLine. You'll see that in the Output window while debugging but it won't affect a Release build at all without the need to modify the code.
    I've used that a lot.

    Most of the time I would leave the "ex" messagebox display. It made phone support easier. It wasn't till towards the end of my career that I started getting remote access. Most of my work the last few years was just maintaining old programs.
    Last edited by wes4dbt; Nov 30th, 2024 at 10:19 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width