Wondering if the following can be done in a simple way:
Try
Some Statements
Catch ex As ...
Error handling stuff
NotCatch
Code to handle *only* if there was no Catch
End Try
A Finally bloc will not do it, because it is executed even if the Catch was executed. Putting the code after the End Try doesn't work either, as it's always executed. I tried to place an Exit Try after the Error handling stuff, but then nothing is executed any more before the End Try.
Is there an clean and easy way to do this without variables to remember that the Catch was executed?
The normal way is like this:
Try
Some Statements
Code to handle *only* if there was no Catch
Catch ex As ...
Error handling stuff
End Try
This works because as soon as an exception is thrown, control jumps to the catch block and the rest of the try block is ignored. Or to put it another way: If a line in the "try" runs, then you know there hasn't been an exception yet.
If you have other requirements that means this wont work then you'll need to provide more information.
Related
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
I'm using VB.NET for the first time, to check if a file is in use, but there are some lines of code that I don't fully understand.
Can someone explain the two lines of code highlighted below in the comments?
Public Sub Main()
IsFileInUse("C:\someFolder\file.pdf")
End Sub
Function IsFileInUse(filePath As String) As Boolean
IsFileInUse = False
If System.IO.File.Exists(filePath) Then
Dim fileInfo As System.IO.FileInfo
Dim stream As System.IO.FileStream
fileInfo = New System.IO.FileInfo(filePath)
Try
' Can someone explain this line of code?
' how does this determines where to go from here, Catch or Finally?
stream = fileInfo.Open(System.IO.FileMode.Open, System.IO.FileAccess.ReadWrite, System.IO.FileShare.None)
Catch
IsFileInUse = True
MessageBox.Show("It looks like the file is opened")
Finally
If stream IsNot Nothing Then
' What is this closing?
stream.Close()
End If
End Try
Else
MessageBox.Show("File does NOT Exist")
End If
End Function
how does this determines where to go from here, Catch or Finally?
Look at the documentation for FileInfo.Open. The Exceptions section shows all of the possible exceptions that can happen.
If an exception is thrown, the Catch block will be executed.
The Finally block always gets executed, whether or not an exception was thrown.
What is this closing?
It will release the stream's resources, in this case it will close the file.
The Try block runs the code. In the Try block, a stream is used to open the file and access its contents. If that code errors for any reason, it will throw an Exception, which will then cause to the Catch block to be run. The Finally block of the code will run whether an Exception is thrown or not. In the Finally block, the stream to the File is being closed.
The code is determining whether or not the file is currently "in use" by any other processes by attempting to open the file with read/write access. Whether the opening of the file fails or not, it always closes the file stream. It assumes that if opening the file in that mode fails for any reason, then it must be because it is "in use". That's a bad assumption to make, and likely not the best way to accomplish it anyway, but for what it's worth, that's what it's doing.
The Try/Catch block is VB.NET's preferred syntax for exception handling (it replaces the older On Error syntax which predated .NET). When anything inside of the Try section throws an exception, execution will jump to the Catch section. Once execution of the Catch section completes, it then jumps to the Finally section. If nothing in the Try section throws an exception, then once it's done, it also jumps to the Finally section. Essentially, everything in the Finally section is "guaranteed" to execute, whether or not an exception occurred, whereas the code in the Catch section only executes when there is an exception.
In other words, consider this example:
' Outputs "ABCE" (does not output "D")
Console.Write("A")
Try
Console.Write("B")
Console.Write("C")
Catch
Console.Write("D")
Finally
Console.Write("E")
And compare it to this example:
' Outputs "ABDE" (does not output "C")
Console.Write("A")
Try
Console.Write("B")
Throw New Exception()
Console.Write("C")
Catch
Console.Write("D")
Finally
Console.Write("E")
See the MSDN article for much more information on the topic.
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
I am pulling my hair out trying to work out an error I'm having with my application. Basically I am getting random errors when trying to populate a dataset from an SQLite query. I can deal with the fact that it might not always return results from the SQLite DB because the tables may be locked, etc. but my code keeps failing and I'm unable to trap the error:
My code looks like this:
Dim ExQry As New SQLiteCommand(QryString, SQLConnect)
ExQry.CommandType = CommandType.Text
Dim da As New SQLiteDataAdapter(ExQry)
dasSpice.Clear()
Try
da.Fill(dasSpice, "Calls") 'Error occurs on this line
Catch ex As SQLiteException
Basically what happens is my code will get to the da.fill(dasSpice, "Calls") statement and throw an error:
A first chance exception of type 'System.Runtime.InteropServices.SEHException' occurred in System.Data.SQLite.dll
However, this error is not caught in the catch statement, but instead my code will skip directly to the cell_formatting event and try to populate my gridview with empty data. Part of my form_load event is to go off and populate the dasSpice dataset and then return to populate another dataset and finally update the gridview. However, because it bombs out on the dasSpice dataset it never returns to populate the second dataset and hence gives me an empty gridview.
Is there anyway at all I can catch this error, or allow my code to return to the form_load event to continue on with the rest of the code? I can provide more detail if required.
Any help would be greatly appreciated as I'm totally at a loss with this. Thanks
You are catching a SqlLiteException by the exception raised is an SEHException.
Try this:
Catch ex As Exception
If TypeOf ex Is SQLiteException Then
.. ... blah
Else
' ... not a SQLiteException so do something else...
End if
Then in .... bits look inside the exception to see what info you can find. How should you diagnose the error SEHException - External component has thrown an exception
Also what is in your query?
You must catch correctly exceptions or base classes from them:
Try
...
Catch ex As SQLiteException 'will handle all SQLiteException (and subclasses not explicitly specified)
...
Catch ex As System.Runtime.InteropServices.SEHException 'Catch all SEHException
...
Catch ex As ... 'Catch another exception
...
Catch ex As Exception 'Catch all remaining exceptions.
...
End Try
See Try/Catch blocks.
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