Finding specific Exceptions using Visual Studio - vb.net

I'm using VS 2010 Express for VB.net and wondering if there is an easy way to discover exceptions that I might encounter by using the IDE?
For example if I have the following:
If Me.saveQueryDialog.ShowDialog() = Windows.Forms.DialogResult.OK Then
Try
sqlTextBox.SaveFile(saveQueryDialog.FileName)
Catch ex As Exception
MessageBox.Show(String.Format("Save was unsuccessful encountered: {0}", ex.Message))
End Try
End If
Can I use the IDE to somehow find that the usual exception I'll encounter in this circumstance is ...ex As IO.IOException
Or in the following:
If Me.openQueryDialog.ShowDialog = Windows.Forms.DialogResult.OK Then
Try
sqlTextBox.LoadFile(openQueryDialog.FileName)
Catch ex As Exception
MessageBox.Show(String.Format("Open was unsuccessful encountered: {0}", ex.Message))
End Try
End If
..the most common exception I'll encounter is ...ex As IO.FileLoadException
Or do I need to just try to remember these specific exceptions?

You can check the MSDN Documentation for each method that you are using to see any possible exception they can throw.
This, for example, are the possible exceptions for .SaveFile() method.

Related

Can get process ID from exception?

Attempting to deploy updates to a .dll using WebClient.DownloadFile. If the dll is loaded/locked by the program it cannot be overwritten, so i'm trying to use a Try... Catch statement (on the following exception) to curate the Process ID and .Dispose() of it.
System.Net.WebException: 'An exception occurred during a WebClient request.'
Inner Exception
IOException: The process cannot access the file 'xyz' because it is being used by another process.
This may or may not be the best methodology... below is my code. Any pointers much appreciated!
Try
Using WC As New WebClient
WC.DownloadFile("https://urlgoeshere.com/library.dll", strLiveDLL)
End Using
Catch ex1 As System.Net.WebException
Using P As Process = ex1.WhatGoesHere 'can get the process ID here??
If MsgBox("Cannot update because dll file is locked by " & P.ProcessName & vbCr &
"Press OK to dispose of this process and continue with update.",
MsgBoxStyle.OkCancel & MsgBoxStyle.Question,
"Update Interrupted") = MsgBoxResult.Ok Then
P.Dispose()
'continue with update
Else
MsgBox("Update Aborted.")
End If
End Using
Catch ex2 As IOException
'
Catch ex3 As Exception
'
End Try
If anyone else is interested, I never figured out how to get the process ID from the exception (I don't think it's possible) but I discovered that it may not be necessary...
What I'm doing instead is just renaming the DLL if it's locked (everything seems to still run as expected even after rename). After it's renamed, the updated DLL can be downloaded to the standard location for the live DLL.

Why does this compile with "Is" but not with "IsNot"?

I'm hacking some old VB code, and I want a function to return early if an exception is caught, but if it's a System.UnauthorizedAccessException the function should continue. Just so I don't get XY'ed, I know this is a strange requirement, but I'm rewriting the code in C#, and I just need to see the result of this. I know there's probably a better way to do it. Here is the original code:
Try
doSomeStuffWithFiles(files)
Catch ex As Exception
MsgBox("Far Field: error in reading / writing to far field file." & Chr(13) & ex.Message)
Exit Sub
End Try
So I added a couple lines:
Catch ex As Exception
MsgBox("Far Field: error in reading / writing to far field file." & Chr(13) & ex.Message)
If TypeOf ex IsNot System.UnauthorizedAccessException Then
Exit Sub
End If
End Try
Now, I'm not an expert in VB, but as far as I can tell this is perfectly valid VB. It also exactly matches the sample code for TypeOf on MSDN. However, this code fails to compile. I get this error:
Error 21 'Is' expected. C:\FilePath 3114 26 Project
Error 22 'UnauthorizedAccessException' is a type in 'System' and cannot be used as an expression. C:\FilePath 3114 32 Project
If I change that line to
Catch ex As Exception
MsgBox("Far Field: error in reading / writing to far field file." & Chr(13) & ex.Message)
If TypeOf ex Is System.UnauthorizedAccessException Then
Exit Sub
End If
End Try
Then everything compiles and runs fine. (Sans the logic being backwards)
I am using visual studio 2013, and targeting .net framework 2.0.
So what's the reason that IsNot is not valid?
It would work as you have it in Visual Studio 2015, but if you look at the VS2013 version of the docs, you'll see only TypeOf ... Is listed, so you'd need to use Not TypeOf ... Is.
Target .NET Framework version doesn't make a difference. If you're using VS2015, TypeOf ... IsNot will compile.
IsNot didn't exist in pre 2.0 .Net VB.Net
If Not TypeOf ex Is
This syntax came from vb6

How to catch an exception and show its details [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about a specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.
Closed 8 years ago.
Improve this question
I'm wondering how I'd go about catching an error and then displaying its details in a custom ListBox or something. The idea is to allow a custom message to appear that's simple, like "Woops, something's went wrong!" but still be able to provide the information for troubleshooting. If someone could help me build this code I'd be really grateful.
So say I have code that could result in an error, like connecting to the internet. How would I be able to catch the error and display it in a separate form (pop-up window)?
I apologize if this seams really basic but I'm new to this stuff and I just don't like the normal error window.
Use following code to output error to user:
Try
'code
Catch ex As Exception
MessageBox.Show(string.Format("Error: {0}", ex.Message))
End Try
I'm wondering how I'd go about catching an error and then displaying
its details in a custom ListBox or something.
If you would like to add the error to a listbox:
Try
'code
Catch ex As Exception
listBox1.Items.Add("Whoops, something went wrong!")
End Try
In the end I ended up with this:
Try
'Code which may error
Catch ex As Exception
MessageBox.Show("Whoops! An error was encountered during the login-in stage. The Server may be offline, un-reachable or your Server Credentials may be in-correct. Please contact U.G Studio for further details. " & _
vbNewLine & "" & vbNewLine & String.Format("Error: {0}", ex.Message))
It allows me to display a custom message whilst still retaining the 'technical' information about the error.
Thanks for the help people!
Here is a code template to get you started:
Try
'Your code
Catch ex As Exception
MessageBox.Show("Woops, something's went wrong!")
'get troubleshooting info out of ex, stack trace perhaps
End Try
If you want something super simple, you could do this:
Try
'Try connecting to the internet
Catch ex As WebException
Dim message = String.Format(
"Encountered an error while connecting to internet: {0}", ex.Message)
MessageBox.Show(message)
End Try
But if you want something a bit more fancy, I'd recommend creating a new form with maybe a Label and RichTextBox on it. You could give it a constructor that takes the exception and will populate the form's controls. I'd use ToString on the exception to show details since this will print out a nice stacktrace and also print out any details of inner exceptions recursively:
Public Sub New(ex As Exception)
InitializeComponent() 'This call is required by Visual Studio.
Me.Label1.Text = String.Format(
"Encountered the following error: {0}", ex.Message)
Me.RichTextBox1.Text = ex.ToString()
End Sub
You could call it from your main form like this:
Try
'Try connecting to the internet
Catch ex As WebException
Dim errorForm = New ErrorForm(ex)
errorForm.Show()
End Try
You could write a function to use in place of MsgBox e.g.:
Public Function LogMsgBox(
ex As Exception,
Prompt As String,
Optional Buttons As MessageBoxButtons = MessageBoxButtons.OK,
Optional Title As String = "OIS Error",
Optional ProgrammerNote As String = "",
Optional SuppressMsgBox As Boolean = False,
Optional FormRef As Object = Nothing) As MsgBoxResult
In the function you can get as fancy as you like - most likely show a dialog box or form more to your liking.
It is handy to log errors so you get feedback on problems. Users just tend to click by problems and not report them.
Also look into Application Framework for VB - it can capture unhandled errors the users also fail to report.

How to detect if file isn't found

I'm a bit new to VB.NET. I was wondering if there was a way to detect if a file being open doesn't exist, then something will happen. Is this possible and is it possible using the "If" statement?
You can use file.exists(filename) to check before you open it, or a try-catch block:
If not System.IO.File.Exists(filename) Then
' file does not exist
end if
or
Try
open ...
Catch ex As Exception
MsgBox(ex.Message) ' not-found error handling goes here
End Try
You can add imports system.io at the top of your file to use File.Exists instead of System.IO.File.Exists.

ftp connection and upload what happens to connection if there is exception

Below is code for how you can upload a file using ftp. My question is what happens if there is an exception in the try, will the ftp connection automatically close in the catch? Is it better to use a "using"?
thank you
Try
'connect to ftp server
Dim ftp As New FTPConnection
ftp.ServerAddress = "ftp.example.com"
ftp.UserName = "example_user"
ftp.Password = "example_pass"
ftp.Connect()
ftp.TransferType = FTPTransferType.BINARY
'upload a file
ftp.UploadFile("s:\test.txt", "test.txt")
'close the connection
ftp.Close()
Catch ex As Exception
MessageBox.Show(ex.Message.ToString())
End Try
When an exception happens (whatever it is) the control flow skips everything until it arrives to a Catch instruction.
So in this case if you have an exception in the UploadFile you will not close the connection.
If the FTPConnection class is IDisposable then your best option is to use the using keyword. Otherwise use the finally statament after the Catch as Grant said.
No, it won't close if an exception occurs before ftp.Close() has finished executing. You should use a Finally block to make sure that ftp is always closed, even if an exception occurs. This means you should define ftp at a higher scope level than within the try block, so that it is accessible within the finally block. You could technically call Close from within the catch block but that A) won't cover both/all circumstances and B) might not work anyway if code in the catch throws yet another exception.
Dim ftp As New FTPConnection
Try
Catch ex As Exception
MessageBox.Show(ex.Message.ToString())
Finally
ftp.Close()
End Try