I would like to catch exceptions to my application startup path in a file called "log_errors" and new exceptions on a new line, instead of messagebox.show:
Try
Dim t As Thread = New Thread(New ThreadStart(AddressOf MySub))
_runningThreads.Add(t)
t.Start()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Answering your specific question, for a very basic logging feature:
Create a "logging" Sub and pass the message to it:
Public Sub LogToFile(ByVal strMessage as String)
' Will create a log_errors.txt file if it doesn't already exist; otherwise, appends to it.
File.AppendAllText(Application.StartupPath & "\log_errors.txt", strMessage)
End Sub
Then in your Catch ex As Exception, instead of:
MessageBox.Show(ex.Message)
do
LogToFile(ex.Message)
Related
I have been struggling with question for some time now and I have tried Everything. there are similar questions on stack overflow but I have tired all solutions none of them worked for me. The problem is changes are not stored on the data base file after I call the data source binding. below is the code snippet for save button
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
If isValidData() = True Then ' sub routine that checks data inputted into textboxes is valid.
Try
' i get data from the textboxes on form which are binded to the bindingsource viewplanet...
Me.ViewPlanetAlliancesBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.DsLab4)
MessageBox.Show("Successfully Saved Data Row")
Call updateViewPlanetAlliance()
Catch ex As DBConcurrencyException
MessageBox.Show("A concurrency erro occured. " & "the row was not deleted.", "Concurrency Exception")
Me.ViewPlanetAlliancesTableAdapter.FillByRegionID(DsLab4.viewPlanetAlliances, CInt(Me.lstRegion.SelectedValue))
Catch ex As ArgumentException
MessageBox.Show(ex.Message, "Argument exception")
Me.ViewPlanetAlliancesBindingSource.CancelEdit()
Catch ex As DataException
MessageBox.Show(ex.Message, ex.GetType.ToString)
Me.ViewPlanetAlliancesBindingSource.CancelEdit()
End Try
Else
Try
Me.TableAdapterManager.UpdateAll(Me.DsLab4)
Catch ex As DBConcurrencyException
MessageBox.Show("A concurrency erro occured. " & "the row was not deleted.", "Concurrency Exception")
Me.ViewPlanetAlliancesTableAdapter.FillByRegionID(DsLab4.viewPlanetAlliances, CInt(Me.lstRegion.SelectedValue))
End Try
End If
End Sub
This is what my form looks like and how my data is displayed
I am using the following code for creating some files.
I have observed that sometimes if some exception occurs all Parallel.For threads stop in between.
I have few questions.
Should I be using AggregateException in CreateReport method or its # rt place.
How to make sure that if exceptions arises in any of the threads it does not stop other parallel threads.
Try
dtScheduledReports = objReprotHelper.GetTopImmediateReportsForExecution()
Parallel.For(0, dtScheduledReports.Rows.Count, Sub(i)
CreateReport(dtScheduledReports.Rows(i))
End Sub)
Catch ae As AggregateException
For Each ex As Exception In ae.InnerExceptions
ExceptionHandler.LogError(ex)
Next
End Try
Private Sub CreateReport(dtRow As DataRow, scheduleType As Integer)
Try
//do something
Catch
throw
End Try
End Sub
You can use a ConcurrentQueue(Of Exception) to enable safe exception enqueueing from multiple threads. This allows to execute the entire loop and throws all exceptions in an AggregateException.
Private Sub DoAParalelJobAndThrowErrors
Dim exQueue as New ConcurrentQueue(Of Exception)
dtScheduledReports = objReprotHelper.GetTopImmediateReportsForExecution()
// Execute the complete loop and capture all exceptions.
Parallel.For(0, dtScheduledReports.Rows.Count, Sub(i)
Try
CreateReport(dtScheduledReports.Rows(i))
Catch ex as Exception
exQueue.Enqueue(ex)
End Try
End Sub)
If exQueue.count > 0 throw new AggregateException(exQueue)
End Sub
Private Sub CreateReport(dtRow As DataRow, scheduleType As Integer)
//do something
End Sub
According MSDN this way doen't break the loop, all rows should be processed.
I get this error. I can not catch it where it comes from. All methods made with try catch but still I get this error from time to time. I used code:
Private Sub add2ComboBox_called(ByVal text As String)
Try
If Me.InvokeRequired Then
Dim args() As String = {text}
Me.Invoke(New Action(Of String)(AddressOf add2ComboBox_called), args)
Return
End If
ComboBox_called.Items.Add(text)
Catch ex As Exception
log_it(ex.StackTrace)
End Try
End Sub
and also this one:
Public Sub clear_do_not_open()
Dim FILENAME As String = path & "\DO_NOT.OPEN"
Dim index As Integer
Try
Using fs As New IO.FileStream(FILENAME, IO.FileMode.Truncate, IO.FileAccess.Write, IO.FileShare.ReadWrite), _
tl As New TextWriterTraceListener(fs)
index = Trace.Listeners.Add(tl)
Trace.Write("")
Trace.Listeners(index).Flush()
Trace.Flush()
End Using
Trace.Listeners.RemoveAt(index)
Catch ex As Exception
log_it(ex.StackTrace)
End Try
End Sub
How do I make this to press Retry by default if it appears? Wait for a second and press Retry again? If not like this then how do I know that this message pops up? If catch the moment it shows up I could then just restart the program or send an email to myselt so I could come to PC where program runs and I could handle it. Now message pops up and program stops while its on.
In my current project I'm sending and receiving textmessages to/from a serversocket/clientsocket (TCP), much like a chat (My project is written in VB.NET). This works as long as I'm converting the bytes sent into strings and presenting them in a msgbox().
This code handles that part:
Try
client = ar.AsyncState
client.EndReceive(ar)
client.BeginReceive(bytes2, 0, bytes2.Length, SocketFlags.None, New AsyncCallback(AddressOf OnRecieve), client)
Try
Dim message As String = System.Text.ASCIIEncoding.ASCII.GetString(bytes2)
MsgBox(message)
Array.Clear(bytes2, bytes2.GetLowerBound(0), bytes2.Length)
Catch ex As Exception
MsgBox("Error writing received message")
End Try
Catch ex As Exception
MsgBox("Error receiving message from server")
End Try
So far so good. However when I try to change "MsgBox(message)" into label1.text = message I get the error: "Error writing received message". My questions, then, is why this happens and what can I do to correct it so that I can have my sockets receiving information that can be added to textboxes and other things in the UI?
Thanks in advance for any help that you can provide
Use a delegate and BeginInvoke() to properly marshal the call to the main UI thread:
Private Sub OnRecieve(ar As IAsyncResult)
Try
client = ar.AsyncState
client.EndReceive(ar)
Try
Dim message As String = System.Text.ASCIIEncoding.ASCII.GetString(bytes2)
NewMessage(message)
Catch ex As Exception
MsgBox("Error writing received message")
Finally
Array.Clear(bytes2, bytes2.GetLowerBound(0), bytes2.Length)
End Try
client.BeginReceive(bytes2, 0, bytes2.Length, SocketFlags.None, New AsyncCallback(AddressOf OnRecieve), client)
Catch ex As Exception
MsgBox("Error receiving message from server")
End Try
End Sub
Private Delegate Sub MessageDelegate(ByVal msg As String)
Private Sub NewMessage(ByVal msg As String)
If Me.InvokeRequired Then
Me.BeginInvoke(New MessageDelegate(AddressOf NewMessage), New Object() {msg})
Else
Label1.Text = msg
End If
End Sub
I am using VS2012 VB.net.
Can I please have some help in creating some code to calculate the error line of an exception and also the function that the exception occurred in.
Here is my current code:
Partial Friend Class MyApplication
Public exceptionListOfExceptionsToNotPauseOn As New List(Of ApplicationServices.UnhandledExceptionEventArgs)
Private Sub MyApplication_UnhandledException(sender As Object, e As ApplicationServices.UnhandledExceptionEventArgs) Handles Me.UnhandledException
Dim msgboxResult As MsgBoxResult
Dim booleanExceptionFoundInList As Boolean = False
'Dim trace As System.Diagnostics.StackTrace = New System.Diagnostics.StackTrace(ex, True)
'Dim exceptionLineNumber = trace.GetFrame(0).GetFileLineNumber()
For x = 0 To exceptionListOfExceptionsToNotPauseOn.Count - 1
If exceptionListOfExceptionsToNotPauseOn(x).Exception.Message = e.Exception.Message Then
booleanExceptionFoundInList = True
End If
Next
If Not booleanExceptionFoundInList Then
msgboxResult = MessageBox.Show("An exception error has occured." & vbCrLf & "Error message: " & e.Exception.Message & vbCrLf & "Do you wish to pause on this exception again?", "Exception", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question)
If msgboxResult = Microsoft.VisualBasic.MsgBoxResult.No Then
exceptionListOfExceptionsToNotPauseOn.Add(e)
End If
End If
e.ExitApplication = False
End Sub
End Class
UPDATE
The code for the trace code uses an Exception data type where as the code for handling unHandled exceptions above has a parameter of "e As ApplicationServices.UnhandledExceptionEventArgs". Can I use the trace code with this data type? Do I need to cast it to an exception type? Or is it not possible?
I am not mastering in Vb.Net but previously i used below code, may be it can help you
[ex.StackTrace()]
Try
'Your Code goes here
Catch ex As Exception
MsgBox(ex.StackTrace())
End Try
Here are a couple of tips. First is to use PostSharp its a AOP kit that will let you trace all methods entry and exit using Attributes. This would direct you to the function straight away.
Another trick. Subscribing to the ThreadExceptionEventHandler actually does cause the debugger to break on unhandled exceptions! Hence temporarily comment out your MyApplication_UnhandledException and add a ThreadExceptionEventHandler
<STAThread> _
Public Shared Sub Main(args As String())
Try
'your program entry point
Application.ThreadException += New ThreadExceptionEventHandler(Application_ThreadException)
'manage also these exceptions
Catch ex As Exception
End Try
End Sub
Private Sub Application_ThreadException(sender As Object, e As ThreadExceptionEventArgs)
ProcessException(e.Exception)
End Sub
Another trick is is not to run under the debugger. The debugger is masking the exception for some reason. If you run your app normally (Ctrl+F5), you'll get the usual Unhandled exception has occurred in your application... Continue/Quit? dialog.
The code for handling unHandled exceptions above has a parameter of "e
As ApplicationServices.UnhandledExceptionEventArgs". Can I use the
trace code with this data type?
No.
You cannot easily use your trace code datatype with the UnhandledExceptionEventArgs. One idea might be to make a class that inherits from UnhandledExceptionEventArgs but I don't know how you'd call the MyApplication_UnhandledException function with the special type, because that function is invoked when an Exception is Unhandled.