Can I catch all possible errors with one message? Vb.net - vb.net

The project I'm working on is almost ready to ship. Occasionally, I'll encounter an error that won't allow the program to continue running like an out of bounds or a memory limitation.
These kinds of errors
I've been fixing them as I find them, but I'm sure there are others. However, I'm leaving this position in a few days so I need the users to not encounter these.
Is there a way in Vb.net that anytime one of those errors wants to pop up, it can catch it with an message box to the user that says something like "Something really bad happened. Please restart program"?

If it's a winform, you can catch the errors by handling the Application.ThreadException event.
AddHandler Application.ThreadException, AddressOf UIThreadException
Private Shared Sub UIThreadException(ByVal sender As Object, ByVal t As ThreadExceptionEventArgs)
' Handle event here and show message
' Exception is in t.Exception
End Sub
Make sure there's no error in this error handler. I don't think it'll catch exception in other threads.

You can use the Try statement, which is a simple way to handle error.
Here is a simple example:
Try
'Do something
Catch ex As Exception
MsgBox("Error occured")
End Try

Related

Catch Exception Message without stopping

I have a simple Try Catch function like:
Try
'do that
Catch
'didn't work now try again
End Try
Now I want the Error / Catch Message to be displayed as Messagebox which works with:
Catch ex As Exception
Messagebox.Show(ex.message)
The issue with that is that it always Stops / Quits the Application after showing me the Error Message which I want to prevent. This should try something until it works and always display the error message without stopping. Is that possible? I need it as compiled exe so just Debugging won't be an option.
As Explanation what I am trying to do:
Basically I have a Timer that executes every 10 Seconds a Request to my Server. It check if my Server is up and connected. If it can't reach my Server it should exactly display me the Message why it didn't connect but it shouldn't stop, it should continue pinging my server 10 seconds later again and try again until it works. The thing is that the exception message sometimes changes so I really need the Exception Message as output
It sounds like right now you have a method that sometimes throws like this:
Public Sub CheckServer()
' do something to test the server
End Function
If the code is not isolated to it's own method like that, it should be.
And you want to call it like this:
Try
CheckServer()
Catch ex As Exception
MessageBox.Show(...)
End Try
I suggest moving the Try/Catch inside the method and making it return a value:
Public Function CheckServer() As String
Try
' do something to test the server
Catch ex As Exception
Return ex.Message
End Try
Return String.Empty
End Function
And then call it like this:
Dim errorMessage As String = CheckServer()
If Not String.IsNullOrEmpty(errorMessage) Then
SendAlert(errorMessage)
End If
Where you also have a separate alert method:
Public Sub SendAlert(alertText As String)
SomeControl.Text += $"{Now} -- {alertText}{vbCrLf}"
End Sub
Notice I did not use MessageBox, because it blocks your UI. But the idea here is this makes it easy to change what you want to do with the alerts when they come in. For example, you might create a toast notification.
Since you're using WinForms, the other thing you could do here is define and then raise an event, rather than returning a value.
Are you using TCPClient to connect ??? If you are, you can just write an IsConnected code. TCP client stays connected until the server or client go out.
The most common error message when a server is not accepting connections is the “server did not properly respond in time message”
Constantly sending the server a request isn’t ideal. You need a one notification to come through when the connection is lost... and then set the timer to constantly try to reconnect.

VB not stopping at exceptions

I like VB.Net, but there is something that is driving me nuts. Too many times when an exception occurs, it simply continues somewhere else, usually by exiting the sub or function, but otherwise keeps on rolling. As an example, I was using Asc() instead of AscW(). It didn't throw an exception, it just left the function as if a Return was executed. Meanwhile I'm leaving red dot stop points all over like it has chicken pox trying to figure out what is causing it.
Is there a setting that can be used to used to actually cause VB to stop and give a line number?
Try catch statements will help you out greatly.
Take a read here: https://msdn.microsoft.com/en-us/library/fk6t46tz.aspx
Have you tried using a Try..Catch..Finally statement. E.g. The ex.string will put the exception into a string in the message and tell you the vb line.
Try
'code here
Catch ex as Exception
MessageBox.Show("Something went wrong. " & ex.ToString, "Data Error ")
End Try

thread pool error trapping

Checking on a best practice here.
I am calling a ThreadPool to run an Async process, specifically sending an SSL email with an attachment which seems to take a good long while.
This is just test code, I thought I would drop this in a Try Catch just incase something failed. But will the thread ever even come back here? I have tested this closing the web page, the browser, clicking the back button on the page. The email always makes it through.
Try
System.Threading.ThreadPool.QueueUserWorkItem(AddressOf DoAsyncWork) '
Catch ex As Exception
Throw ex
Exit Sub
End Try
I am not trying to force a failure, yet I guess, but I would like to know how best to trap if the thread fails.
Protected Sub DoAsyncWork(ByVal state As Object)
Dim oMyObject As New sendSSLemail
oMyObject.SSL(userName, , strMessageBody, emailAdd, , permFileLocation, , "CodeMsg")
End Sub
A more convenient way of doing work with the thread pool is to use Task.Factory.StartNew(Action). It returns a Task object which can be Awaited or blocked on with Wait.
Once the task completes, the Exception property of the Task can be used to determine whether an exception was thrown and unhandled by the task's subroutine. (If it's not Nothing, then the InnerException property has the real exception that was thrown.)
Dim task = Task.Factory.StartNew(AddressOf WorkFunction)
' do stuff that doesn't depend on WorkFunction having completed
task.Wait()
If task.Exception IsNot Nothing Then Throw task.Exception.InnerException
After a Throw, the sub is exited anyway (the call stack is unwound looking for a Catch), so the Exit Sub statement does nothing. Wrapping a QueueUserWorkItem call in a try block also does nothing, because any exception would occur on the other thread. You would only get exceptions thrown immediately by QueueUserWorkItem, which off the top of my head only includes complaints about the delegate being Nothing.
Asynchronous tasks can also return values. For more information on that, see the TaskFactory methods that return a Func(Of Task).

Repeated error handling

So in my vb.net application, i've got alot of try and catch blocks for error handling, especially whenever my app talks to the db.
i'm running through a series of if/elseif statements to see if
ex.tostring.contains("Unable to connect to any of the specified MySQL hosts")
and various bits like that.
At the minute, I wrote this out and copy and pasted it into each catch, but I know there will be a much more efficient way to do this whereby the code is just in one place and called as and when required.
I tried to implement it as a function, but I had trouble passing info to the function.
So i thought I'd ask and see how you guys go about doing this?
You don't need multipe try...catch statements for a program. One is enough.
If i understood you correctly, you want to print or show the error that occured inside the Try block.
Public Sub main()
Try
'Do something
Catch ex As Exception
End Try
Try
'Do something else
Catch ex As Exception
End Try
If ex.tostring.contains("something") than
End Sub
Instead you can do something like this:
Public Sub main()
Try
'Do all your code here.
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
In this part, the compiler will automaticlly print the error occured in the program.
You can perform some action based on the type of exception thrown. Checking the text if not recommended as this could change with a new version of .net or mysqldata
Try something like this:
Try
'
' Programming lines of code
'
Catch exError As MySqlException
' an error occurred with MySql
Catch e As Exception
' a General error occurred
Finally
' Cleanup custom and unmanaged resources if necessary
End Try
Have a look at the MySQL Documentation for their recommendations

Is there a better way to get visual studio to ignore try/catch in debug mode

I want the designer to catch the error when I am debugging and I want the user to see my friendly message if an error occurs for them. I know I can acomplish this with the following:
#If Debug=False Then
Try
#End If
'some code here
#If Debug=False Then
Catch ex as exception
Messagebox.Show("Errors suck")
End Try
#End If
I do not want to have to write all the #statements and having them cluttering up my code. It seems like this should be a common need and there has to be a better way. Does anyone know a better way?
In VS.NET you can say whether you want the debugger to break when an exception is thrown (not just when it's unhandled).
Look on the Debug | Exceptions... menu item (Ctl-Alt-E on my keyboard shortcuts). Pick the excepption you're interested in, then tick the "thrown" box for that exception.
You can tick that box at several levels (all CLR exceptions, all CLR exceptions in a given namespace, or very specific exceptions)
There is no good way to get it to ignore a try catch other than what you've done. But you can make the code a little bit cleaner and essentially get the same effect. You essentially are trying to prevent the action in the catch block from running. A better way to do that is a conditionally compiled method.
Try
...
Catch ex As Exception
DebugLog(ex)
Throw
End Try
<Condition("DEBUG)> _
Public Sub DebugLog(ByVal ex As Exception)
Messagebox.Show("errors suck")
End Sub
In the catch section of your Try..Catch you should write the exception message, stacktrace, and anything else you may want to a log file -- additionally you could write that data to the Windows Event log as well.
At worst, you could just put break-points in the Catch section of your Try..Catch blocks, since you shouldn't normally hit them it should'nt be a big deal once setup.
Here is how I do it:
Enabled:
Try ' : Catch: End Try
doSomething
andSomeMore
etcEtc
' Try
Catch ex As Exception
handleException
End Try
Disable the above by deleting the two comment characters:
Try : Catch : End Try
doSomething
andSomeMore
etcEtc
Try
Catch ex As Exception
handleException
End Try