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
Related
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.
I have already found this: Get Exception type from an exception
The given answer is exactly what I had in my code, but the type "SAP.Middleware.Connector.RfcCommunicationException" is not defined in my SAPConnector as it seems.
The relevant piece of code looks like this:
Public Sub RFC_Connect()
Dim rfcFunctionStandort As IRfcFunction
Try
'Build RFC-Connection
RfcDestinationManager.RegisterDestinationConfiguration(New SAP_Connect)
rfcDestination = RfcDestinationManager.GetDestination("SomeDestination")
Catch ex As SAP.Middleware.Connector.RfcCommunicationException
'Connection Refused
'Set the app to Offline-Mode
Catch ex As Exception
frmHauptmenue.txtEdit.ErrorLog(ex.Message)
End Try
End Sub
When running this without the first catch-statement it throws the "RfcCommunicationException" stated above.
Public Sub RFC_Connect()
Dim rfcFunctionStandort As IRfcFunction
Try
'Build RFC-Connection
RfcDestinationManager.RegisterDestinationConfiguration(New SAP_Connect)
rfcDestination = RfcDestinationManager.GetDestination("SomeDestination")
Catch ex As Exception
frmHauptmenue.txtEdit.ErrorLog(ex.Message)
End Try
End Sub
The import of the connector itself is done and working:
Imports SAP.Middleware.Connector
The SAP NCo3 consists of two DLLs: sapnco.dll and sapnco_utils.dll. Did you perhaps reference only one of these in your Visual Studio project? In my project I have no problem using the RfcCommunicationException!
In fact: Visual Studio shows that RfcCommunicationException is exported from the sapnco_utils assembly. That gives me another idea: sapnco.dll is basically platform-independent, but sapnco_utils.dll contains unmanaged C/C++ modules and therefore needs to be used in a platform-dependent way (either 32bit/x86 or 64bit/x64)! So two other possible causes of your problem might be:
You have defined your Visual Studio project as "Mixed platform"
You have defined your Visual Studio project as x86, but downloaded/installed the x64 version of NCo3, or vice versa (defined the project as x64 and downloaded x86 version).
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.
I'm writing a windows service which runs as the local system account. I'm trying to make sure if I have full read/write access to a file beginning to process it any further. Here is my code:
Dim FullPath As String
FullPath = "C:\directory\file.txt"
Dim ps As Security.PermissionSet
ps = New Security.PermissionSet(Security.Permissions.PermissionState.Unrestricted)
ps.AddPermission(New Security.Permissions.FileIOPermission(Security.Permissions.FileIOPermissionAccess.AllAccess, FullPath))
ps.AddPermission(New Security.Permissions.FileIOPermission(Security.Permissions.FileIOPermissionAccess.AllAccess, IO.Path.GetDirectoryName(FullPath)))
Try
ps.Demand()
Catch ex As Security.SecurityException
System.Diagnostics.EventLog.WriteEntry("ShopLink", "File " + FullPath + " will not be parsed. " + ex.Message)
Exit Sub
Catch ex As Exception
System.Diagnostics.EventLog.WriteEntry("ShopLink", "File " + FullPath + " will not be parsed. " + ex.Message)
Exit Sub
End Try
Then I set the full access permissions for the file to "Deny" for the user account my service is running as. After executing, the code above doesn't throw any exceptions and allows file processing to begin. When the service later tries to change and/or delete the file, I get an "Access Denied" exception.
Any suggestions?
For this purpose i use thise small function:
Private Function HasAccess(ByVal ltFullPath As String)
Try
Using inputstreamreader As New StreamReader(ltFullPath)
inputstreamreader.Close()
End Using
Using inputStream As FileStream = File.Open(ltFullPath, FileMode.Open, FileAccess.ReadWrite, FileShare.None)
inputStream.Close()
Return True
End Using
Catch ex As Exception
Return False
End Try
End Function
In your case then:
If HasAccess(FullPath) ...
I have solved the problem by using My.Computer.FileSystem.DeleteFile to delete the file instead of Kill. My.Computer.FileSystem.DeleteFile was executed without problems after successfully demanding full read/write access to the file in the way described above, while Kill consistently threw an "Access denied" exception.
Using "Kill"... I know this is a very old thread but I'll add this in case anyone stumbles on it like I did. I was working on some old VB6 legacy code. One of my clients users was getting a runtime exception during a file open after a kill. The code was "Killing" the file and then rebuilding it from scratch with binary data held in memory. It tuns out that the "Kill" function triggered the user's anti-virus software which locked the file long enough to cause the next "Open" statement to fail. I discovered this using an error logging utility (the name escapes me at the moment). The line in the error log file on the failed "Open" statement was that the file's status was "Delete pending" due to the user's anti-virus software.
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.