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.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I have a power on-off device to control. If the device is connected to the network, my code works fine. I remove the device from the network on purpose to test it as if the device malfunctions (like power off). And I find out that the System hangs.
I trace that the socket.accept does not execute - 'accept is ok' is not written to a log file. ex.message does not write as well.
My purpose is to send a message to support if there is any device malfunction.
Using gSocket As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
WriteLog("Start. ")
Dim remoteSocket As Socket
Try
gSocket.SendTimeout = 5000
gSocket.ReceiveTimeout = 5000
gSocket.Bind(vEndPoint) ' vEndpoint is the local machine
WriteLog("bind is ok. ")
gSocket.Listen(10)
WriteLog("listen is ok. ")
remoteSocket = gSocket.Accept
WriteLog("accept is ok. ")
Catch ex As Exception
WriteLog(ex.Message)
Finally
End Try
How can I solve this?
I use BeginAccept to solve it.
Dim acceptResult As IAsyncResult = gSocket.BeginAccept(Nothing, Nothing)
Dim Success As Boolean = acceptResult.AsyncWaitHandle.WaitOne(vTimeout, True)
If Success Then
remoteSocket = gSocket.EndAccept(acceptResult)
WriteLog("beginaccept is ok. ")
Else
gSocket.Close()
WriteLog("beginaccept failed. ")
End If
i have try to add some data into the access database VIA VB2008, when i pull in no issue using their original function, where there is add, delete and save button on top of it, but when i am creating the function on the button, found that 1st data able to add, second data unable to add, it show "too many field to defined" appreciate someone can help out, i go through many link, i am copy exactly what they have done.
i have tried remove the ID (auto generate number in access) but still fail. no article on it
If Button2.Text = "New" Then
Try
BEFOREBindingSource.AddNew()
MsgBox("successful")
Catch ex As Exception
MsgBox("Error during Add")
Exit Sub
End Try
ElseIf Button2.Text = "Save" Then
Try
'Me.BEFOREBindingSource.EndEdit()
' Me.TableAdapterManager.UpdateAll(Me.MPCINSPECTION2DataSet)
BEFOREBindingSource.EndEdit()
BEFORETableAdapter.Update(MPCINSPECTION2DataSet.BEFORE)
Catch ex As Exception
MsgBox("Error during save")
Exit Sub
End Try
End if
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'm currently talking to another computer to see what events they have occurring. I have setup a Wql Event query like so below:
Console.WriteLine("Polling...")
Try
Dim query As New WqlEventQuery("SELECT * FROM Lnl_AccessEvent")
Dim accessEventWatcher = New ManagementEventWatcher("SELECT * FROM Lnl_AccessEvent")
accessEventWatcher.Start()
accessEventWatcher.WaitForNextEvent()
Console.WriteLine("AccessEvent Occured.")
Catch ex As Exception
Console.WriteLine(ex.Message + " " + ex.StackTrace)
End Try
On the ".Start()" line, I get an exception stating "Invalid class" and "ManagementException". I know the connection is working since before this instance I'm able to connect and get the basic info from the remote computer's WMI, like IP address. The only solutions I have found is that has to do with my target build being only x86, but now it's at AnyCPU and still has this issue.
What is causing this error?
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.