Let exceptions thrown or check in VB.NET (performance-vise) - vb.net

Let's say we have a
Dictionary(Of Date, List(Of SomeClass))
And we got ~ a million rows in a database, so I am curious which one is better performance-wise, to check if my Dictionary has key, or adding directly in try catch clause without checking it?
While Reader.Read
Try
MyDictionary.Add(Reader("SaleDate"), New SomeClass(Reader("SaleData")))
Catch ex As Exception
' Silence here
End Try
End While
While Reader.Read
Try
If Not MyDictionary.ContainsKey(Reader("SaleDate")) Then
MyDictionary.Add(Reader("SaleDate"), New SomeClass(Reader("SaleData")))
End If
Catch ex As Exception
MsgBox("ERROR")
End Try
End While

You should not worry about performance until you have a performance issue.
You should never catch exception if you do not expect it and have a recovery plan and there is no other way to check and see if there will be an exception.
Exceptions are a good thing. There are there to protect you and your application users. So don't abuse them or catch them every where.

Related

Is there a time when Exception can be nothing?

while trying to maintain someone else's code I found this little gem:
Catch ex As Exception
If Not ex Is Nothing Then
...
End If
Finally
Is there a time when this could happen that I am unaware of? Should I be adding these to my code?
If you try this:
Try
Dim x As Exception = Nothing
Throw x
Catch ex As Exception
Debug.Print(ex.ToString())
End Try
ex will be a System.NullReferenceException. The Throw statement docs don't mention what happens if you pass a null reference, but the OpCodes.Throw docs say:
NullReferenceException is thrown if the object reference is a null reference.
So, I believe the answer is that ex can never be Nothing.
Unless there is a GoTo statement which resets the Exception ex thrown to Nothing, the code seems redundant since the only case in which the control enters the Catch is when there is an Exception thrown from Try block while the If Not condition compares default value of Nothing which equals Exception. Meaning the condition would never be satisfied and stands redundant except for some GoTo control which assigns a different Exception to Nothing,

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

Can't catch exception with DataAdaptor.Fill command and sqlite

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.

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

Can I dispose of these unmanaged resources without requiring a reference to each?

I have a class bMainframe that manages the connections to 4 different mainframes. It allows for the same underlying unmanaged library to be opened in specific ways and more than one mainframe to be connected to at a time. Each library has its own disposal code for the unmanaged mainframe connection resource. The wrapper also has code that calls the individual mainframe connection's disposal code.
This causes an error if someone's project does not make use of all 4 mainframes, but calls the disposal on the wrapper. (FileLoadException could not load assembly X of the 4 managed mainframes) Since that disposal code checks to see which of the 4 are not nothing/null. Even if nothing/null this is causing .net to try to load the assembly and crash.
Is the disposal code in the outer wrapper helpful or necessary? is there a way to check if the assembly for a type is even loaded that doesn't trigger.net to load the type/assembly?
I modified the code below to block the fileloadexception, but I don't believe this is the best way.
Protected Overridable Sub Dispose(ByVal disposing As Boolean)
If Not Me.disposedValue Then
If disposing Then
' TODO: free managed resources when explicitly called
End If
Try
If Me._Linx IsNot Nothing Then
If _Linx.cnLinx IsNot Nothing Then
Try
_Linx.Disconnect()
Catch ex As Exception
Trace.WriteLine("Error doing linx.disconnectSession")
End Try
Try
_Linx.Dispose()
Catch ex As Exception
Trace.WriteLine("Error doing linx.dispose")
End Try
End If
End If
Catch ex As IO.FileLoadException
Debug.WriteLine("Failed to load LinxFile")
End Try
Try
If Me._Acaps IsNot Nothing Then
_Acaps.Disconnect()
_Acaps.Dispose()
End If
Catch ex As IO.FileLoadException
Debug.WriteLine("Failed to load AcapsFile")
End Try
Try
If Me._Dart IsNot Nothing Then
Try
_Dart.Dispose()
Catch ex As Exception
Trace.WriteLine("Error disposing of Dart")
End Try
End If
Catch ex As IO.FileLoadException
Debug.WriteLine("Failed to load DartFile")
End Try
Try
If LpsOpen Then
Try
_Lps.Dispose()
Catch ex As Exception
Trace.WriteLine("Error disposing of Lps")
End Try
End If
Catch ex As IO.FileLoadException
Debug.WriteLine("Failed to load LpsFile")
End Try
' TODO: free shared unmanaged resources
End If
Me.disposedValue = True
End Sub
check out this post which should allow you to see which assemblies are loaded
How to retrieve info on a loaded assembly at runtime? (c# , .NET)
Perhaps this could be handled with four separate classes inheriting from a base class that would have slightly different implementation in their dispose functions... then you can iterate through an array and dispose them all if you are using more than one in some case. Something doesn't seem right about having to figure out what resources are included at run-time in this particular use since you know the different mainframes at design time.
Also, after you've released objects for the garbage collector to pick up, it may be a good idea to run GC.Collect() so the garbage collector runs immediately.