Is there a time when Exception can be nothing? - vb.net

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,

Related

How to write 'if not caught' code in a Try Catch

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.

Try-Catch exception handler VB.NET

I'm working through a Hair Salon application in VB.NET. Basically the user is able to select the stylist, service(s), age category and enter the number of visits. I then have a Calculate button in order to calculate the total price. I'm required to use Try-Catch for exception handling but I'm not too familiar with it. I'm assuming it's used for error handling, in which case how would I check to see if client visits is greater than 0 and to check to see if the value entered is an integer? Here is what I've tried with the client visits:
Try
(intClientVists > 0)
Exit Try
Catch ex As Exception When
(intClientVists < 0)
Exit Try
End Try
Just hoping someone can steer me in the right direction because I'm not really sure what I'm doing for this particular aspect of the application. Thanks.
Yes, Try/Catch blocks are used for error handling. However, they're not really for this kind of error. Try/Catch blocks are more for errors made by the programmer or the computer (could not allocate memory, could not connect to database, could not open a file, tried to divide by zero, could not cast a value to the specified type) than for errors made by the user (entered a wrong number).
Instead, you want a simple If/Else block:
If intClientVists > 0 Then
'Do something
Else
'Do something else
End If
If you really want to use exception handling for this (again: not normally the best choice), here is how it might look:
Try
If intClientVists < 0 Then Throw New InvalidOperationException()
'Data is OK. Continue processing here
Catch Ex As InvalidOperationException When intClientVisits = 0
'Show one error message
Catch Ex As InvalidOperationException When intClientVisits < 0
'Show different error message
End Try
This MSDN article gives you a list of .NET exceptions that you can use in a Try-Catch. These are actual errors as opposed to input validation checking, like Joel explained.
Basically, you put some logic in the Try block, and if you want to do something in the case of a specific exception, then you catch that exception type and put your logic in that Catch block. Then as a "catch-all" just simply catch "Exception" to do something no matter what type the exception is.
In your particular case, it sounds like the most likely use of a Try-Catch would be if the user inputs the number of visits into a regular text box in which they could enter letters. Here is an example of what you could do for that:
Try
If CInt(txtNumVisits.Text) > 0 Then
'logic here
End If
Catch ex As Exception
'If user entered something other than an integer in that box then an InvalidCastException will be caught
'enter logic here for if that's the case. For example:
MessageBox.Show(Me, "Please enter a number >= 0", "Invalid Input")
txtNumVisits.Focus()
End Try

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.

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

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.

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