Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Exceptions help
#2
To answer your first question, it is generally a good idea to make sure that your program is free of obvious errors instead of handling them with Try/Catch blocks. For example, you can use a Try/Catch block to catch any errors that may occur during the reading of a file if the file doesn't exist, but it would be much better to do something like this:
[code2=vb.net]If (My.Computer.Filesystem.FileExists(path)) Then
My.Computer.Filesystem.DeleteFile(path)
Else
MsgBox("The file does not exist!")
End If[/code2]
In this way, you are not forcing the program to break its current flow due to exceptions and you are also catching the error and letting the user know what the problem is. This can be done for anything, for example, an "Object Reference" error when selecting items from a ListBox
[code2=vbnet]Try
MsgBox(ListBox1.SelectedItem.ToString)
Catch ex As Exception

End Try[/code2]
The above code definitely catches the error, but it doesn't really do anything about it. This is considered bad practice. We want to ensure that everything is okay before calling ListBox1.SelectedItem.ToString in order to prevent any errors from occurring. So a better solution would be:
[code2=vbnet]If Not (ListBox1.SelectedItem Is Nothing) Then
MsgBox(ListBox1.SelectedItem.ToString)
End If[/code2]
But it really all depends on a person's programming style.


To answer your second question, the finally block does not disregard any actual errors that would occur, so it would throw a second exception in your specific case. One way to prevent this is by using the above methods for checking/preventing errors. So something like this would solve your problem
[code2=vb.net]Try
My.Computer.Network.DownloadFile(localPath, remotePath)
Catch ex As Exception
'Some error occurred during the download!
Finally
If (My.Computer.Filesystem.FileExists(localPath)) Then
My.Computer.Filesystem.DeleteFile(localPath)
End If
End Try[/code2]

In this way, you are catching any error that may occur during the download and also deleting the file if it exists.

I hope this helps!
My Blog | My Setup | My Videos | Have a wonderful day.


Messages In This Thread
Exceptions help - by brco900033 - 08-04-2013, 08:28 AM
Re: Exceptions help - by brandonio21_phpbb3_import2 - 08-04-2013, 11:21 PM
Re: Exceptions help - by brco900033 - 08-05-2013, 03:12 AM

Forum Jump:


Users browsing this thread: 1 Guest(s)