-
Nov 29th, 2024, 04:57 AM
#1
Thread Starter
Addicted Member
[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.
-
Nov 29th, 2024, 08:46 AM
#2
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.
-
Nov 29th, 2024, 09:16 AM
#3
Re: How to use Try... Catch in following code?
ἄνδρα μοι ἔννεπε, μοῦσα, πολύτροπον, ὃς μάλα πολλὰ
πλάγχθη, ἐπεὶ Τροίης ἱερὸν πτολίεθρον ἔπερσεν·
-
Nov 29th, 2024, 09:29 AM
#4
Re: How to use Try... Catch in following code?
Originally Posted by sapator
greece-gold-price ???
Relax, it's only goverment selling sovereign gold for peanuts. . . Just what EU told them to do :-))
cheers,
</wqw>
-
Nov 29th, 2024, 10:23 AM
#5
Re: How to use Try... Catch in following code?
WHAT?! HOW DARE YOU?!
That is....
Accurate.
ἄνδρα μοι ἔννεπε, μοῦσα, πολύτροπον, ὃς μάλα πολλὰ
πλάγχθη, ἐπεὶ Τροίης ἱερὸν πτολίεθρον ἔπερσεν·
-
Nov 29th, 2024, 12:09 PM
#6
Member
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
-
Nov 29th, 2024, 02:46 PM
#7
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
-
Nov 29th, 2024, 03:48 PM
#8
Re: How to use Try... Catch in following code?
Originally Posted by Red.x
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.
-
Nov 29th, 2024, 04:11 PM
#9
Member
Re: How to use Try... Catch in following code?
Originally Posted by Niya
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
-
Nov 29th, 2024, 04:55 PM
#10
Re: How to use Try... Catch in following code?
Originally Posted by Red.x
Help him out
Don't talk like a grandma
I already did. This is the answer:-
Originally Posted by Niya
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.
-
Nov 29th, 2024, 06:27 PM
#11
Re: How to use Try... Catch in following code?
Originally Posted by Red.x
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.
-
Nov 29th, 2024, 07:47 PM
#12
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
-
Nov 29th, 2024, 07:51 PM
#13
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
-
Nov 29th, 2024, 11:36 PM
#14
Thread Starter
Addicted Member
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.
-
Nov 29th, 2024, 11:55 PM
#15
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.
-
Nov 30th, 2024, 12:36 AM
#16
Thread Starter
Addicted Member
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.
-
Nov 30th, 2024, 01:49 AM
#17
Re: How to use Try... Catch in following code?
Originally Posted by marsias
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.
-
Nov 30th, 2024, 02:49 AM
#18
Thread Starter
Addicted Member
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.
-
Nov 30th, 2024, 08:31 AM
#19
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.
-
Nov 30th, 2024, 03:00 PM
#20
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
-
Nov 30th, 2024, 03:16 PM
#21
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.
-
Nov 30th, 2024, 04:14 PM
#22
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.
-
Nov 30th, 2024, 05:25 PM
#23
Re: How to use Try... Catch in following code?
Originally Posted by PlausiblyDamp
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.
-
Nov 30th, 2024, 09:42 PM
#24
Re: How to use Try... Catch in following code?
Originally Posted by wes4dbt
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.
-
Nov 30th, 2024, 10:15 PM
#25
Re: How to use Try... Catch in following code?
Originally Posted by jmcilhinney
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|